我一直在使用相对定位的元素来垂直居中。但是,我从未理解为什么position: relative; top: 50%;
不会垂直居中元素,或至少将元素的上边缘置于其容器div中。
position: relative
:
布置所有元素,就像元素没有定位一样,然后调整元素的位置,而不改变布局
MDN关键字:
指定元素移动到正常位置以下的数量。
top
关键字上的top
值:
是包含块高度的百分比
因此,值为top: 50%
的相对定位的元素应该向下移动50%的包含块高度,对吗?这是不是意味着该元素的上边缘恰好位于包含元素的中间?
请考虑以下代码段:
.container {
overflow: hidden;
width: 90%;
height: 90%;
margin: 0 auto;
background-color: #eee;
}
.child {
width: 40%;
height: 40%;
margin: 0 auto;
background-color: #444;
border-top: 5px solid #f00;
}
.top-50-percent {
position: relative;
top: 50%;
}
.contract-and-expand {
animation-name: contract-and-expand;
animation-duration: 5s;
animation-iteration-count: infinite;
animation-timing-function: ease-in-out;
}
@keyframes contract-and-expand {
50% {
height: 0%;
}
}
<html>
<head>
<style>
/* Just initial/basic CSS rules here to make this look better */
@import url("https://necolas.github.io/normalize.css/latest/normalize.css");
* {
box-sizing: border-box;
margin: 0;
}
html, body {
height: 100%;
}
body {
color: #aaa;
}
.center-vertically {
position: relative;
top: 50%;
transform: translateY( -50% );
}
p {
position: absolute; /* Remove paragraphs from flow so they don't interfere */
}
</style>
</head>
<body>
<div class="container center-vertically contract-and-expand">
<p>Container Wrapper</p> <!-- Paragraphs are removed from the flow -->
<div class="child top-50-percent">
</div>
</div>
</body>
</html>
从代码段看起来顶边是居中的。这总是正确的吗?这是类似的小提琴:%
当视口的高度被拉起时,子元素的顶部边框不再看起来居中。
答案 0 :(得分:0)
我用Inkscape和2(黄色)垂直方块测量了相同的大小。这是一种视错觉。上边缘实际上从来没有在那个小提琴中偏离中心。此外,我的所有假设都是正确的:相对定位元素上的<img class="stocktonPics" src="images/stockton0.jpg" alt="slides">
会将该元素的顶部边框向下移动到容器高度的50%。这个元素没有完全垂直居中的原因是上边缘是在相对定位元素上使用top:50%
时的轴心点。