简体   繁体   English

CSS-如何将div相对于作为封面的背景图像居中

[英]CSS - How to center a div relative to a background image positioned as cover

I'm trying to center a div relative to another div which has a background image positioned as cover. 我正在尝试将一个div相对于另一个div居中,该div的背景图像定位为封面。

html: 的HTML:

<div id="back">
  <div id="box">
    <p>test 1</p>
    <p>test 2</p>
    <p>test 3</p>
  </div>
</div>

css: CSS:

#back{
   position: absolute;
   top: 0;
   left: 0;
  right: 0;
  bottom: 0;
  background: url('https://upload.wikimedia.org/wikipedia/commons/thumb/e/e1/White_square_in_purple_background.svg/450px-White_square_in_purple_background.svg.png');
  background-repat: no-repeat;
  background-position: 50%;
  background-size: cover;
}

#box{
  position: absolute;
  top:10%;
  left: 20%;
  bottom: 10%;
  right: 20%;
  background: red;
}

here's a fiddle: 这是一个小提琴:

http://jsfiddle.net/8x7tgrqm/ http://jsfiddle.net/8x7tgrqm/

I'm trying to center the red div always inside the white box in background at different screen sizes. 我试图将红色div始终以不同屏幕尺寸在背景中的白框内居中放置。 Try to resize the window to see what I mean. 尝试调整窗口大小以了解我的意思。 I was wondering if there is a way in CSS or even JS to have the box always centered into the background white box. 我想知道CSS或JS中是否有一种方法可以使框始终居中于背景白框内。

thanks 谢谢

Here is a solution using the awesome vmax unit: 这是使用超赞的vmax单元的解决方案:

http://jsfiddle.net/x5m3w40o/2/ http://jsfiddle.net/x5m3w40o/2/

#box{
    position: absolute;
    top:50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width:57vmax;
    height:57vmax;
    background: red;
}  

You probably need to adjust the 57 vmax value to something like 58-59 to make it completely cover the white rectangle in this particular case. 在这种特殊情况下,您可能需要将57 vmax值调整为58-59,以使其完全覆盖白色矩形。

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

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