前端开发中几种居中方式

感谢原作者的分享,让我对居中有了充分的认识,填补了空缺部分

原文地址:https://juejin.im/post/5b9a4477f265da0ad82bf921

下文中widthF widthS 这俩个样式是父元素的宽高以及背景色的设置

father_x son_x 设置布局方式

.widthF {
    width:300px;
    height: 300px;
    background: red;
}
.widthS {
    width: 100px;
    height: 100px;
    background: gray;
}

1、第一种方式通过父节点定义为相对定位,子元素使用绝对定位,通过top,left使得子元素居中

.father_1 {
    position: relative;
}

.son_1 {
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -50px;
    margin-top: -50px;
}

<div class="father_1 widthF">
            <div class="son_1 widthS">
            </div>
 </div>

这种方式需要知道子元素的宽高

2、第二种方式想将每个方向上的偏移量设置为0,然后设置margin为auto就可以使得子元素居中

.father_2 {
    position: relative;
}
.son_2 {
    position: absolute;
    margin: auto;
    left: 0;
    right: 0;
    bottom: 0;
    top: 0;
}

<div class="widthF father_2">
            <div class="widthS son_2">
                
            </div>
        </div>

原文作者说这种方式的缺点是需要知道子元素的宽高,但是并不需要知道子元素的宽高

3、使用calc计算属性计算left top的值达到居中的效果

.father_3 {
    position: relative;
}
.son_3 {
    position: absolute;
    left: calc(50% - 50px);
    top: calc(50% - 50px);
}

<div class="widthF father_3">
            <div class="widthS son_3">
                
            </div>
        </div>

这种方式需要知道子元素的宽高

4、通过transform中translate属性来控制水平和垂直方向上的偏移量

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

<div class="widthF father_4">
            <div class="widthS son_4">
                <strong>4</strong>
            </div>
        </div>

5、将子元素设置为行内元素,可以使用行内元素的属性

.father_5 {
    text-align: center;     // 将父元素类的行内元素水平居中
    line-height: 300px;   // 行高要等于父元素的高度
}
.son_5 {
    display: inline-block;
    vertical-align: middle;  // 垂直方向居中
    line-height: initial;/*不设置为初始值,行高默认继承父元素的行高*/
}

6、css-table方式实现居中  将父级元素设置为table-cell格式,子元素设置为inline-block,然后设置垂直居中属性即可

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

<div class="widthF father_6">
            <div class="widthS son_6">
                <strong>6</strong>
            </div>
        </div>

7、使用flex布局实现居中

.father_7 {
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
}
.son_7 {
    
}

<div class="widthF father_7">
            <div class="widthS son_7">
                <strong>7</strong>
            </div>
        </div>

只要设置了父元素的布局方式,子元素会按照方式进行布局

8、Grid布局

.father_8 {
    display: grid;
}
.son_8 {
    align-self: center;
    justify-self: center;
}

<div class="widthF father_8">
            <div class="widthS son_8">
                <strong>8</strong>
            </div>
        </div>
    </body>

这种方式的浏览器兼容性存在问题,优先推荐使用flex

  • PC端有兼容性要求,宽高固定,推荐absolute + 负margin
  • PC端有兼容要求,宽高不固定,推荐css-table
  • PC端无兼容性要求,推荐flex
  • 移动端推荐使用flex

猜你喜欢

转载自blog.csdn.net/w123452222/article/details/82697319