简体   繁体   English

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

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

As you can see, I'm trying to make container which a background-image responsive when I minimize my browser's window. 如您所见,当我最小化浏览器窗口时,我试图使container具有background-image响应。

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

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 CodePen

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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM