块元素居中方法汇总

411 阅读2分钟

居中问题无论在工作还是在面试中, 都是很常见的 下面我来给大家总结几种常用的方法, 大家可根据实际情况选择 好了, 废话不多说, 先看下效果

1. 定位+偏移 (margin)

  • html
<div class="father">
    <div class="son"></div>
</div>
  • css
.father {
    position: relative;
    width: 1000px;
    height: 600px;
    background: lightblue;
}
.son {
    position: absolute;
    width: 100px;
    height: 100px;
    background: yellow;
    top: 50%;
    margin-top: -50px; /* 高度的一半 */
    left: 50%;
    margin-left: -50px; /* 宽度的一半 */
}

2. 定位+偏移 (transform)

如果绝对定位元素的尺寸是已知的, 也没有必要使用下面这种用法, 因为在有些场景下, 百分比 transform 会让iOS 微信闪退, 还是尽量避免的好

  • html
<div class="father">
    <div class="son"></div>
</div>
  • css
.father {
    position: relative;
    width: 1000px;
    height: 600px;
    background: lightblue;
}
.son {
    position: absolute;
    width: 100px;
    height: 100px;
    background: yellow;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

3. 利用 margin: auto; 自动分配多余空间 (推荐)

  • html
<div class="father">
    <div class="son"></div>
</div>
  • css
.father {
    position: relative;
    width: 1000px;
    height: 600px;
    background: lightblue;
}
.son {
    position: absolute;
    width: 100px;
    height: 100px;
    background: yellow;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    margin: auto;
}

top、left、right、bottom 的值相等即可,不一定要都是0

注: 定位元素需设置宽高

4. Flex 布局

  • html
<div class="father">
    <div class="son"></div>
</div>
  • css
.father {
    width: 1000px;
    height: 600px;
    background: lightblue;
    display: flex;
    align-items: center; /* 垂直居中 */
    justify-content: center; /* 水平居中 */
}
.son {
    width: 100px;
    height: 100px;
    background: yellow;
}

5. text-align: center; + vertical-align: middle;

  • 原理 当 daughter 高度设为100%并增加 vertical-align: middle; 属性后, son 底部基线会自动对齐 daughter 中间位置

  • html

<div class="father">
    <div class="son"></div>
    <div class="daughter"></div>
</div>
  • css
.father {
    width: 1000px;
    height: 600px;
    background: lightblue;
    text-align: center;
}
.son {
    display: inline-block;
    width: 100px;
    height: 100px;
    background: yellow;
    vertical-align: middle;
}
.daughter {
    display: inline-block;
    width: 0;
    height: 100%;
    vertical-align: middle;
}