这是 jsfiddle:http://jsfiddle.net/techsin/1o5zzcgh/
我想在不使用 jquery 的情况下将两个绝对定位的 div 居中。现在我正在使用 top:0 和 bottom 0,但是当定义了高度时,这不起作用。
* {
margin: 0;
padding: 0;
}
html, body {
position: relative;
height: 100%;
width: 100%;
}
.in, .out {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
.in {
background-color: red;
height: 50%;
}
.out {
background-color: blue;
}
最佳答案
你可以使用这个小技巧:
HTML:
<div class="out">
<div class="in">
</div>
</div>
CSS:
.in, .out {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
.in {
background-color: red;
height: 50%;
left: 50%;
top: 50%;
-moz-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
-o-transform: translate(-50%, -50%);
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
.out {
background-color: blue;
}
通过使用 left/top 和 translate minus values,您可以根据需要居中。
HTH.
关于html - 您如何在绝对 div 中将绝对 div 居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29187039/