本文转至http://www.html5dw.com/post?id=1433
水平居中:行内元素解决方案
只需要把行内元素包裹在一个属性display为block的父层元素中,并且把父层元素添加如下属性即可:
- .parent {
- display:flex;
- justify-content:center;
- }
垂直居中:未知高度的块状元素解决方案
- .item{
-
- top: 50%;
-
- position: absolute;
-
- transform: translateY(-50%);
-
- }
水平垂直居中:未知高度和宽度元素解决方案
- .item{
-
- position: absolute;
-
- top: 50%;
-
- left: 50%;
-
- transform: translate(-50%, -50%);
-
- }
水平居中:行内元素解决方案
只需要把行内元素包裹在一个属性display为block的父层元素中,并且把父层元素添加如下属性即可:
- .parent {
- text-align:center;
- }
水平居中:块状元素解决方案
- .item {
-
- margin: 10px auto;
- }
垂直居中:多行的行内元素解决方案
组合使用display:table-cell和vertical-align:middle属性来定义需要居中的元素的父容器元素生成效果,如下:
- .parent {
-
- background: #222;
-
- width: 300px;
-
- height: 300px;
-
-
-
- display: table-cell;
-
- vertical-align:middle;
-
- }
水平垂直居中:已知高度和宽度的元素解决方案1
这是一种不常见的居中方法,可自适应,比方案2更智能,如下:
- .item{
-
- position: absolute;
-
- margin:auto;
-
- left:0;
-
- top:0;
-
- right:0;
-
- bottom:0;
-
- }
水平垂直居中:已知高度和宽度的元素解决方案2
- .item{
-
- position: absolute;
-
- top: 50%;
-
- left: 50%;
-
- margin-top: -75px;
-
- margin-left: -75px;
-
- }