css实现水平垂直居中的方法

2019-03-06  本文已影响0人  Melantha_CHEN

本文主要针对子元素已知宽高和未知宽高的情况下,对其进行水平垂直居中

  本文假设对如下元素进行水平垂直居中方式(父元素和子元素):

<div class="parent">
    <div class="children size"></div>
</div>

首先给他们加一个公共使用的样式(本文介绍的方法有定宽和不定宽的,所以size用来表示children的宽高)

.parent {
   border: 1px solid red;
   width: 600px;
   height: 600px;
}
.children {
    background: green;    
}
.children .zise {
    width: 200px;
    height: 200px;
}

子元素相对父元素进行绝对定位,左和上边距为50%,此时子元素左上顶点在元素的正中间,只需要让子元素的中心点在父元素正中间即可:

1. absolute + 负margin

.parent {
    position: relative;
}
.children {
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -100px;
    margin-left: -100px;
}

2. absolute + margin auto

通过设置各个方向距离都是0,然后再将margin设为auto

.parent {
    position: relative;
}
.children {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
}

absolute + calc

calc()属于CSS3,用于动态计算长度值。

.parent {
    position: relative;
}
.children {
    position: absolute;
    top: calc(50% - 100px);
    left: calc(50% - 100px);
}

以下方法都是子元素未知的情况:

4. absolute + transform 移动

使用css3新属性transform的translate, 其属性的百分比是相对于自身的宽和高进行移动。

.parent {
    position: relative;
}
.children {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
}

在一些浏览器中可能会出现模糊,是因为元素有可能被放置在办个像素的位置上,可通过以下方法解决此问题:
transform-style: preserve-3d;

5. line-height 属性

利用行内元素的属性实现居中:

.parent {
    line-height: 600px;
    text-align: center;
}
.children {
    display: inline-block;
    vertical-align: middle;
    line-height: initial;
}

6. writing-mode

writing-mode可以改变文字的显示方向,比如可以通过writing-mode让文字的显示变为垂直方向:

<div class="div1">水平方向</div>
<div class="div2">垂直方向</div>
.div2 {
    writing-mode: vertical-lr;
}

这样可以改变文字的显示方向
具体实现方式如下:

<div class="wp">
    <div class="wp-inner">
        <div class="box"></div>
    </div>
</div>

.wp {
    writing-mode: vertical-lr;
    text-align: center;
}
.wp-inner {
    writing-mode: horizontal-tb;
    display: inline-block;
    text-align: center;
    width: 100%;
}
.box {
    display: inline-block;
    margin: auto;
    text-align: left;
}

7. table

tabel单元格中的内容天然就是垂直居中的,只要添加一个水平居中属性就好了,table会增加代码的冗余性:

<table>
    <tbody>
        <tr>
            <td class="parent">
                <div class="children">子元素-表格</div>
            </td>
        </tr>
    </tbody>
</table>

.parent {
        text-align: center;
    }
.children {
    display: inline-block;
}

8. css-table

css新增的table属性,可以让我们把普通元素,变为table元素的现实效果,通过这个特性也可以实现水平垂直居中:

.parent {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}
.box {
    display: inline-block;
}

9. flex

.parent {
    display: flex;
    justify-content: center;
    align-items: center;
}

10. grid

css新出的网格布局,但是兼容性不好

.wp {
    display: grid;
}
.box {
    align-self: center;
    justify-self: center;
}

总结:

注:本文主要参考此篇文章CSS实现水平垂直居中的1010种方式(史上最全)

上一篇 下一篇

猜你喜欢

热点阅读