I'm trying to center a div relative to another div which has a background image positioned as cover.
html:
<div id="back">
<div id="box">
<p>test 1</p>
<p>test 2</p>
<p>test 3</p>
</div>
</div>
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:
I'm trying to center the red div always inside the white box in background at different screen sizes. 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.
thanks
Here is a solution using the awesome vmax unit:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.