css居中常见方法总结

块级元素居中 html代码部分

<div class="parent">
   <div class="child">child</div>
</div>

行内元素居中 html代码部分

<div class="parent">
   <span class="child">child</span>
</div>

水平居中

1. 行内元素 text-align: center;

.parent {
   text-align: center;
}

.

2. 块级元素 margin: auto;

.child {
    width: 100px;
    margin: auto; 
}

垂直居中

1. 行内元素(单行文字垂直居中):设置 line-height = height

.parent {
   height: 200px;
   line-height: 200px;
}

.

2. 块级元素:绝对定位(需要提前知道尺寸)

优点:兼容性不错
缺点:需要提前知道尺寸,margin-top: -(高度的一半); margin-left: -(宽度的一半);

.parent {
    position: relative;
    height: 200px;
}
.child {
    width: 80px;
    height: 40px;
    position: absolute;
    left: 50%;
    top: 50%;
    margin-top: -20px;
    margin-left: -40px;
}

.

3. 块级元素:绝对定位 + transform(常用

优点:不需要提前知道尺寸
缺点:css3属性存在兼容性问题

.parent {
    position: relative;
    height: 200px;
}
.child {
    width: 80px;
    height: 40px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%); // 有兼容性问题
}

.

4. 块级元素:绝对定位 + margin: auto;(常用

优点:不需要提前知道尺寸,兼容性好
缺点:这个方法是我最喜欢用的一个,要说缺点的话,我目前还不知道。

.parent {
    position: relative;
    height: 200px;
}
.child {
    width: 80px;
    height: 40px;
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    margin: auto;
}

.

5. 块级元素:display: table-cell

.parent {
    width: 600px;
    height: 200px;
    border: 1px solid red;
    display: table;
}
.child {
    display: table-cell;
    vertical-align: middle;
}

.parent {
    height: 300px;
    border: 1px solid red;
    display: table-cell;
    vertical-align: middle;
}

.

6. 块级元素:display: flex(常用

flex布局 yyds~

.parent {
    width: 600px;
    height: 200px;
    border: 1px solid red;
    display: flex;  /*兼容性问题*/
    align-items: center; /*垂直居中*/
    justify-content: center; /*水平居中*/
}

.

7. 块级元素:calc()

缺点:需要提前知道尺寸,css3属性存在兼容性问题

.parent {
    width: 300px;
    height: 300px;
    position: relative;
}
.child {
    width: 100px;
    height: 100px;
    background: blue;
    padding: -webkit-calc((100% - 100px) / 2);
    padding: -moz-calc((100% - 100px) / 2);
    padding: -ms-calc((100% - 100px) / 2);
    padding: calc((100% - 100px) / 2); /*计算出平均间距*/
    background-clip: content-box;
}
posted @ 2022-07-20 18:15  猫老板的豆  阅读(166)  评论(0编辑  收藏  举报