How to make background image fit correctly inside a board without losing responsiveness

前端 未结 3 915
旧巷少年郎
旧巷少年郎 2021-01-06 20:36

I have code in which there is class box, i have given backgroundimage to class box box1.

my problem is that the im

相关标签:
3条回答
  • 2021-01-06 20:45

    I suggest you give your body a background-position according to your requirements. usually centering it is the best choice:

    background-position: center center;
    

    You can see how it works by looking at the snippet. resize the image by its bottom-right handle.

    div{
    	background-image: url('//unsplash.it/500');
    	background-size:cover;
    	background-position:center;
    	resize:both;
    	overflow:auto;
    	width:100%;
    	height:200px;
    }
    <div></div>

    0 讨论(0)
  • 2021-01-06 21:04

    I think you are tackling this the wrong way. I would instead extract the board element from the main background and use it as an element alone:

    html {
      background: #afffdc;
    }
    
    #container {
      position: fixed;
      bottom: 0;
      left: 100px;
      background: url(https://i.stack.imgur.com/CM15R.jpg) top/contain no-repeat;
      height: 50vh;
      width: 29vh;
      max-width: 20vw;
      max-height: 35vw;
    }
    
    .box {
      padding-top: 173%;
      background: url(https://picsum.photos/200/300) 50% 5%/86% 27% no-repeat;
    }
    <div id="container">
      <div class="box">
      </div>
    </div>

    Update

    Here is a transparent version

    html {
      background: linear-gradient(to right,pink, lightblue);
    }
    
    #container {
      position: fixed;
      bottom: 0;
      left: 100px;
      background: url(https://i.stack.imgur.com/ctB0T.png) top/contain no-repeat;
      height: 50vh;
      width: 29vh;
      max-width: 20vw;
      max-height: 35vw;
    }
    
    .box {
      padding-top: 173%;
      background: url(https://picsum.photos/200/300) 50% 5%/86% 27% no-repeat;
    }
    <div id="container">
      <div class="box">
      </div>
    </div>

    0 讨论(0)
  • 2021-01-06 21:06

    If you want your image to cover it's container you can use background-size: cover;,

    If you want make sure the whole image is being displayed (but being resized if needed), you can use background-size: contain;

    The above two requires explicit width & height in the class box1

    0 讨论(0)
提交回复
热议问题