Trouble making a div with a background-image with fixed height and width responsive

你说的曾经没有我的故事 提交于 2020-01-06 14:33:45

问题


As you can see, I'm trying to make container which a background-image responsive when I minimize my browser's window.

I've tried playing with max-width ,percentages, background-size:cover and a few other tricks but they didn't work or they made my container disappear.

Pug

section
  div(class='container')

SASS

section
  height: 100vh
  width: 100vw
  background: gray
  .container
    position: absolute
    background: url('https://www.triplejtours.com.au/wp-content/uploads/2016/02/Lake-Kununurra-reflections-Dylan-Lodge.jpg')
    background-repeat: no-repeat
    background-position: center
    background-size: cover
    height: 807px
    width: 948px
    left: 50%
    top: 50%
    transform: translate(-50%,-50%)

CodePen


回答1:


You can try something like this:

body {
  margin: 0;
}

.container {
  height: 100vh;
  width: 100vw;
  display: flex; /*use flex to easily center*/
  background: gray;
}

.container>div {
  background: url('https://www.triplejtours.com.au/wp-content/uploads/2016/02/Lake-Kununurra-reflections-Dylan-Lodge.jpg');
  background-repeat: no-repeat;
  background-position: center; /*keep it center within the centred div*/
  background-size: contain; /*use contain to make the image shrink visually*/
  width: 100%;
  height: 100%;
  margin: auto; /*center the div*/
  max-width: 948px; /*Image width*/
  max-height: 807px; /*Image height*/
}
<div class="container">
  <div></div>
</div>


来源:https://stackoverflow.com/questions/51050709/trouble-making-a-div-with-a-background-image-with-fixed-height-and-width-respons

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!