更新时间:2022-11-01 21:13:23
。阅读此文件。
http: //css-tricks.com/centering-in-the-unknown/
如果您想要纵向&水平中心到未知高度,宽度元素。您必须将父级的样式作为display:table,将child的样式作为display:table-cell。
// UPDATED
如果你知道高度&
.parent {
display:block;
position:relative;
}
.child {
display:block;
height:x;
width:y;
position:absolute;
top:50%;
left:50%;
margin-top:-x / 2; //一半的负方向的高度
margin-left:-y / 2; //宽度减半方向
}
How can we center (horizontally and vertically) the text in this div?
HTML
<div class="text">
hello is the the testhello is the the testhello is the the testhello is the the testhello is the the testhello is the the
testhello is the the tes
</div>
CSS
.text {
width:150px;
background:red;
float:left;
height:150px;
margin:10px;
text-align:center;
word-wrap:break-word;
overflow:hidden;
color:white;
}
Here is the full explanation here. Read this.
http://css-tricks.com/centering-in-the-unknown/
If you want to vertical & horizontal center to unknown height, width element. you must add the style for parent as display:table and the style for child as display:table-cell.
//UPDATED
if you know the height & width of the element.
Try this.
.parent {
display:block;
position:relative;
}
.child {
display:block;
height:x;
width:y;
position:absolute;
top:50%;
left:50%;
margin-top:-x/2; //Half of the height with minus direction
margin-left:-y/2; //Half of the width with minus direction
}