使用固定高度和宽度的背景图像使div响应困难

时间:2018-06-26 20:12:29

标签: html css sass pug

如您所见,当我最小化浏览器窗口时,我试图使container成为background-image的响应。

我尝试过使用max-widthpercentagesbackground-size:cover和其他一些技巧,但它们没有起作用,或者使我的容器消失了。

哈巴狗

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 个答案:

答案 0 :(得分:1)

您可以尝试以下操作:

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>

相关问题