在寫網頁時經常要做到對齊以及居中等,下面就來淺談水準居中以及垂直居中。
水準居中
- text-align:center實作行内元素水準居中。
- margin:0 auto實作塊元素水準居中。
- 使用CSS3中新增的transform屬性。
.parent{
position:relative;
}
.son{
position:absolute;
left:50%;
transform:translate(-50%,0);
}
- 使用flex 布局
.box{
display: flex;
justify-content: center;
}
5.使用絕對定位方式, 以及負值的margin-left,margin-left是width的一半。
.parent{
position:relative;
}
.son{
position:absolute;
width:100px;
left:50%;
margin-left:-50px;
}
6.使用絕對定位方式, 以及left:0;right:0;margin:0 auto;
.parent{
position:relative;
}
.son{
position:absolute;
width:100px;
left:0;
right:0;
margin:0 auto;
}
垂直居中
- 設定 line-height 等于父元素高度
.box{ height:20px;line-height :20px}
2.使用flex 布局
.parent {
display: flex;
align-items: center;
}
3.可用 transform
.parent{
position:relative;
.son{
position:absolute;
top:50%;
transform: translate(-50%,-50%);
}
4.使用絕對定位方式, 以及負值的margin-top,margin-top是width的一半
.parent{
position:relative;
}
.son{
position:absolute;
height:100px;
top:50%;
margin-top:-50px;
}
5.使用絕對定位方式, 以及left:0;right:0;margin:0 auto;
.parent{
position:relative;
}
.son{
position:absolute;
height:100px;
left:0;
right:0;
margin:0 auto;
}
6.若元素是行内塊級元素, 基本思想是使用display: inline-block, vertical-align: middle和一個僞元素讓内容塊處于容器中央.
.parent::after, .son{
display:inline-block;
vertical-align:middle;
}
.parent::after{
content:'';
height:100%;
}
7.元素高度不定時, 可用 vertical-align 屬性, 而vertical-align隻有在父層為 td 或者 th 時, 才會生效, 對于其他塊級元素, 例如 div、p 等, 預設情況是不支援的. 為了使用vertical-align, 我們需要設定父元素display:table, 子元素 display:table-cell;vertical-align:middle;
參考文章