Skip to content

Instantly share code, notes, and snippets.

@zhouyanyu
Last active June 14, 2020 05:30
Show Gist options
  • Save zhouyanyu/924126b44faaa4c75182dc8bf0e30402 to your computer and use it in GitHub Desktop.
Save zhouyanyu/924126b44faaa4c75182dc8bf0e30402 to your computer and use it in GitHub Desktop.
title date tags categories
老生常谈,关于元素居中
2017-10-19 07:08:17 -0700
Css
Css

在元素居中的这个问题上,已经是个老生常谈的问题了。其实,说来说去无外乎那么几种,这次好好地做个总结。

以下是我们给的两个div,以及默认样式:

<div class="dad">
    <div class="son"></div>
</div>
.dad{
    background-color: #eee;
    width: 500px;
    height: 300px;
}
.son{
    background-color: red;
    width: 100%;
    height: 100px;
}

垂直居中

垂直居中实现效果: 垂直居中

absolute + transform

当我们使子元素距离父元素50%的时候,我们还要给子元素负位移回自身高度50%

.dad{
    position: relative;
}
.son{
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
}

inline-block + table-cell + vertical-align

这种方法对子元素仅需要一个约束就是为行内块,而父元素需要需要变成表格以及垂直对齐。

.dad{
    display: table-cell;
    vertical-align: middle;
}
.son{
    display: inline-block;
}

flex + align-items: center

这一种使用了比较新的flex布局,仅需要对父元素flex和垂直对齐即可。这个以后要好好整理一遍。

.dad{
    display: flex;
    align-items: center; 
}

水平居中

我们这次把子元素宽带调为父80%,实现水平居中。

.dad{
    background-color: #eee;
    width: 500px;
    height: 300px;
}
.son{
    background-color: red;
    width: 100%;
    height: 100px;
}

水平居中实现效果: 水平居中

margin: 0 auto

方便快捷的margin左右auto

.son{
    margin: 0 auto;
}

text-align: center + inline-block

就像使文字居中那样,使行内块居中

.dad{
    text-align: center;
}
.son{
    display: inline-block;
}

flex + justify-content:center

同样的道理,flex的水平居中。😌不考虑兼容,使用flex真实爽啊!

.dad{
    display:flex;
    justify-content:center;
}

总结

总结了这几种比较常用的,再想到再添加上去。 垂直:

  1. absolute + transform
  2. inline-block + table-cell + vertical-align
  3. flex + align-items: center

水平:

  1. margin: 0 auto
  2. text-align: center + inline-block
  3. flex + justify-content:center
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment