css居中顯示
阿新 • • 發佈:2021-01-21
技術標籤:css
CSS塊級元素居中顯示
<div class="parent">
<div class="child">居中</div>
</div>
一、子控制元件確定寬度高度
水平居中
.parent{
width: 600px;
height: 600px;
background-color: #eee;
}
.child{
width: 300px;
height: 300px;
background-color: aqua;
margin : 0 auto;
}
垂直居中
.parent{
width: 600px;
height: 600px;
background-color: #eee;
position: relative;
}
.child{
width: 300px;
height: 300px;
position: absolute;
top: 50%;
left: 50%;
background-color: aqua;
margin-top: -150px;
margin-left: -150px;
}
二、子控制元件不確定寬度高度
水平居中
需要居中的元素寬度不確定,根據它的內容撐開。
.parent{
width: 600px;
height: 600px;
background-color: #eee;
position: relative;
}
.child{
position: absolute;
left: 50%;
background-color: aqua;
transform: translate(-50%)
}
垂直居中
需要居中的元素高度不確定,根據它的內容撐開。
.parent {
width: 600px;
height: 600px;
background-color: #eee;
position: relative;
}
.child{
position: absolute;
top: 50%;
left: 50%;
background-color: aqua;
transform: translate(-50%,-50%)
}