如何在div中垂直居中HR标记,我试过了,但它没有完全居中
.container {
position: relative;
width: 80vw;
height: 40vh;
border: solid 4px #333;
}
hr {
height: 5px;
background-color: cadetblue;
position: absolute;
right: 0;
top: 50%;
left: 0;
transform: translateY(-100%);
}
<div class="container">
<hr>
</div>
更大的问题是,您需要通过添加margin:0
来从hr
中删除任何裕度
此外,通过将transform:translateY()
更改为top:calc()
并删除bottom:
,您可以获得更简洁易懂的代码
.container {
position: relative;
width: 80vw;
height: 40vh;
border: solid 4px #333;
}
hr {
height: 4px;
margin:0;
background-color: cadetblue;
position: absolute;
right: 0;
top: calc(50% - 2px);
left: 0;
}
<div class="container">
<hr>
</div>
将transform
更改为translateY(-50%);
,并将margin: 0;
添加到hr
:
(BTW:如果您有定义的height
,则不需要top
和bottom
设置,有其中一个就足够了(
.container {
position: relative;
width: 80vw;
height: 40vh;
border: solid 4px #333;
}
hr {
height: 5px;
background-color: cadetblue;
position: absolute;
right: 0;
top: 50%;
left: 0;
transform: translateY(-50%);
margin: 0;
}
<div class="container">
<hr>
</div>
无需在css中使用transform
。
.container {
position: relative;
width: 99%;
height: 50vh;
border: solid 4px #333;
}
hr {
height: 5px;
background-color: blue;
position: absolute;
right: 0;
left: 0;
top: calc(50% - 5px);
margin: 0;
}
<div class="container">
<hr>
</div>
在顶级中定义您的hr
高度