如果知道父類的高度,文字居中可以直接用line-height
屬性來做帝璧。
但是如果父類的高度是會變化的,比如下面的demo湿刽,會隨body來變化,則需要用絕對定位
和位偏移
屬性了褐耳。
參考資料
CSS3 transform-translate
CSS 絕對定位
話不多說诈闺,直接上代碼
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body {
width: 100%;
height: 100%;
}
.parent {
position: absolute;
width: 500px;
height: 500px;
background-color: palevioletred;
}
.children {
position: absolute;
top: 50%;
left: 50%;
width: 100px;
height: 100px;
line-height: 100px;
text-align: center;
color: #fff;
background-color: rebeccapurple;
}
</style>
</head>
<body>
<div class="parent">
<div class="children">我要居中</div>
</div>
</body>
</html>
使用了絕對定位之后,過頭了
可以看到铃芦,并沒有居中雅镊,有點過頭了,因為還忽略了紫色模塊的高度和寬度刃滓。
如果要紫色模塊在粉色模塊中垂直居中仁烹,紫色模塊距離粉色模塊的頂部的距離,應(yīng)該是50%的粉色高度 - 50% 的紫色高度咧虎,水平居中的寬度同理卓缰。
所以這時候,可以用CSS3的位偏移,挪回去征唬。
transform: translate(-50%, -50%);
完整代碼:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body {
width: 100%;
height: 100%;
}
.parent {
position: absolute;
width: 500px;
height: 500px;
background-color: palevioletred;
}
.children {
position: absolute;
top: 50%;
left: 50%;
width: 100px;
height: 100px;
line-height: 100px;
text-align: center;
transform: translate(-50%, -50%);
color: #fff;
background-color: rebeccapurple;
}
</style>
</head>
<body>
<div class="parent">
<div class="children">我要居中</div>
</div>
</body>
</html>
居中啦