給定基礎結果如下所示:實現content的水平和垂直居中的方式:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>居中</title>
<style type="text/css">
.container{
width:100px;
height:100px;
background: red;
}
.content{
width:50px;
height:50px;
background: green;
}
</style>
</head>
<body>
<div class="container">
<div class="content"></div>
</div>
</body>
</html>
方式1:將content元素變爲inline-block,利用text-align的使其水平居中,在父元素中通過 vertical-align: middle; display: table-cell;使元素垂直居中,vertical-align該屬性定義行內元素的基線相對於該元素所在行的基線的垂直對齊。允許指定負長度值和百分比值。這會使元素降低而不是升高。在表單元格中,這個屬性會設置單元格框中的單元格內容的對齊方式。
.container{
width:100px;
height:100px;
background: red;
text-align: center;
vertical-align: middle;
display: table-cell;
}
.content{
width:50px;
height:50px;
background: green;
display: inline-block;
}
方式二:利用flex方式實現垂直和水平居中,該方式也有兩種方式,這是其中一種,利用父元素的屬性align-items實現垂直居中
.container{
width:100px;
height:100px;
background: red;
display: flex;
justify-content: center;
align-items: center;
}
.content{
width:50px;
height:50px;
background: green;
}
方式三:將上面的垂直居中方式改爲利用子元素的align-self使其垂直居中,其屬性值和align-items是一樣的,只是這個是單獨作用域該元素的,如果是使用的父元素的屬性,則是作用域所有的子元素
.container{
width:100px;
height:100px;
background: red;
display: flex;
justify-content: center;
}
.content{
width:50px;
height:50px;
background: green;
align-self: center;
}
方式四:利用定位實現,利用定位也有兩種方式,其中一種需要知道寬高,即下面的方式,另外一種不需要見方法五
.container{
width:100px;
height:100px;
background: red;
position: relative;
}
.content{
width:50px;
height:50px;
background: green;
position: absolute;
left:50%;
top:50%;
margin-left: -25px;
margin-top: -25px;
}
方法五:
.container{
width:100px;
height:100px;
background: red;
position: relative;
}
.content{
width:50px;
height:50px;
background: green;
position: absolute;
left:50%;
top:50%;
transform:translate(-50%,-50%)
}
方式六:不常見的一種方式
.container{
width:100px;
height:100px;
background: red;
text-align: center;
}
.container:before{
content: '';
display: inline-block;
vertical-align: middle;
height:100%;
width:100%;
}
.content{
width:50px;
height:50px;
background: green;
display: inline-block;
vertical-align: middle;
margin-top:-125px;
}