CSS居中对齐

CSS实现居中对齐的几种方式

页面布局中,居中对齐是我们经常遇到的场景,现在总结几个常用的方式供大家参考。

场景一:按钮文字居中对齐,line-height + text-align

html代码:

<div class="btn">Hello World</div>

CSS代码:

.btn{
  width: 120px;
  height: 48px;
  border: none;
  background: #f8f8f8;
  color: #333;
  /* 文本水平居中 */
  text-align: center;
  /* 文本垂直居中 */
  ling-height: 48px;
}

效果如图所示:

场景二:父元素内部的子元素居中对齐,子元素设置position定位来实现

方式1:position+top/left定位实现

HTML代码:

<div class="father">
    <div class="son"></div>
</div>

CSS代码:

.father {
    width: 400px;
    height: 400px;
    margin: 0 auto;
    margin-top: 100px;
    background: lightblue;
    /*子元素定位可以是相对定位,也可以是绝对定位,所以父元素最好做定位限制。*/
    position: relative;
 }

.son {
    width: 100px;
    height: 100px;
    border: none;
    background: #1c3beb;
    /* 居中代码,定位可以是相对定位,也可以为绝对定位 */
    position: relative;
    top: calc(50% - 50px);
    left: calc(50% - 50px);
}
方式2:position+top/left+transform来实现居中

上面的子元素的偏移量计算,也可以由CSS3中的新属性transform来实现:

.son {
    width: 100px;
    height: 100px;
    border: none;
    background: #1c3beb;
    /* 居中代码,定位可以是相对定位,也可以为绝对定位 */
    position: absolute;
    top: 50%;
    left: 50%;
    /*百分比是相对于自身宽高的偏移量计算*/
    transform: translate(-50%, -50%);
}
方式3:position+margin来实现居中

上面的子元素也可以利用绝对定位元素的流体特性和margin:auto的自动分配特性来实现居中:

.father {
    width: 400px;
    height: 400px;
    margin: 0 auto;
    margin-top: 100px;
    background: lightblue;
    position: relative;
 }

.son {
    width: 100px;
    height: 100px;
    border: none;
    background: #1c3beb;
    /* 居中代码,定位为绝对定位 */
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
}
方式4:弹性布局实现居中
.father {
    width: 400px;
    height: 400px;
    margin: 0 auto;
    margin-top: 100px;
    background: lightblue;
    /*启用弹性布局,主轴与交叉轴都采用居中对齐*/
    display: flex;
    justify-content: center;
    align-items: center;
}

.son {
    width: 100px;
    height: 100px;
    border: none;
    background: #1c3beb;
}

以上几种对齐效果都一样,但是考虑到兼容性等问题,推荐方式3。以上几种方式的对齐效果如下:

posted @ 2020-07-03 18:18  老甄Home  阅读(504)  评论(0编辑  收藏  举报