2016-06-28 138 views
3

我是新来的,完全被某物困住了。我有div背景图片。当调整窗口大小时,一旦调整窗口小于实际照片的宽度,背景图像的高度就会缩小。我喜欢这样看起来的样子,但div容器保持相同的高度。我拥有的任何文本都不会保持垂直居中于背景图片(高度发生变化),而是保持居中居中(不是),所以文本从图像上浮起。有没有办法让容器以与背景图像相同的方式缩小,这样一切都保持居中?背景图像收缩但不是div

#mainpic { 
 
    margin: 0; 
 
    width: 100%; 
 
    height: 400px; 
 
    background-image: url("http://www.aclefproductions.com/Images/pianoedit6.jpg"); 
 
    background-size: 100%; 
 
    background-repeat: no-repeat; 
 
    overflow: hidden; 
 
    display: flex; 
 
    align-items: center; 
 
    justify-content: center; 
 
}
<div id="mainpic"> 
 
    <h3>Hello</h3> 
 
</div>

回答

0

也许这就是你想要什么?见http://codepen.io/8odoros/pen/dXvzBq?editors=1100#

#mainpic { 
      margin: 0; 
      width: 100%; 
      background-image: url("http://www.aclefproductions.com/Images/pianoedit6.jpg"); 
      background-size: 100%; 
      background-repeat: no-repeat; 
      overflow: hidden; 
      display: flex; 
      align-items: center; 
      justify-content: center; 
} 
#mainpic h3{ 
      height:400px; 
} 
1
<div id = "mainpic"> 
    <h3>Hello</h3> 
    <img src="http://www.aclefproductions.com/Images/pianoedit6.jpg"> 
</div> 

#mainpic { 
    margin: 0; 
    position: relative; 
    } 

    #mainpic img{ 
    width: 100%; 
    } 


    #mainpic h3{ 
    position: absolute; 
    top: 50%; 
    left: 50%; 
    transform: translate(-50%, -50%); /*To account for the width and hight of the h3*/ 
    margin: 0; 
    } 

https://jsfiddle.net/4p3gek5x/

享受

+0

谢谢!这正是我的想法! –