css实现居中的方法

水平居中

1. 行内设置text-align

给父元素设置text-align为center,一般用于实现文字水平居中

2. 给当前元素设置margin:0 auto

原理:块级独占一行,表现为在水平方向上占满整个父容器,当水平方向padding,border,width成定值时,margin左右为auto,默认margin左右平分剩余空间

<head>
    <style>
        .content{
            width: 600px;
            height: 300px;
            border: 1px solid #000;
        }
        .box{
            width: 200px;
            height: 200px;
            background-color: darkcyan;
            margin: 0 auto;
        }
    </style>
</head>
<body>
    <div class="content">
        <div class="box"></div>
    </div>
</body>

但是当该元素设置了position为absolute时,需要加上left为0,right为0才能使margin:0 auto生效,让元素左右边界都紧贴其包含块的边缘。

.box{
    width: 200px;
    height: 200px;
    background-color: darkcyan;
    margin: 0 auto;
    left: 0;
    right: 0;
    position: absolute;
}

3. justify-content

父元素设置display为flex布局,justify-content为center,设置盒子在主轴的对齐方式为center

.content{
   width: 600px;
   height: 300px;
   border: 1px solid #000;
   display: flex;
   justify-content: center;
}

4. transform + position

父元素设置relative,子元素设置absolute,left为50%,距离左边偏移父元素50%,transform为translateX(-50%),向左平移自身宽度的50%

5. margin-left + position

与transform类似,只是margin-left为负的自身宽度的一半

当未知宽高时用transform,已知宽高可以用margin-left

垂直居中

1. 单行文本可以设置line-height

设置line-height与height相等

一般用于文字垂直居中

2. align-items

父元素设置flex,align-items为center,定义元素在侧轴对齐方式为center

3. transform + position

与水平居中一样,设置top:50%距离上边偏移父元素50%,transform为translateY(-50%)

4. margin-top + position

与水平居中一样,设置top:50%,margin-top:负的自身高度的一半

5. margin:0 auto

子元素设置absolute定位,top为0,bottom为0,margin设置auto

.box{
    width: 200px;
    height: 100px;
    background-color: darkcyan;
    position: absolute;
    margin: auto;
    top: 0;
    bottom: 0;
}

6. table-cell + vertical-align

给父元素设置display为table-cell,vertical-align为middle

整体居中

行内:text-align:center; line-height:height

块级:

1. flex

.content{
    width: 400px;
    height: 300px;
    border: 1px solid #000;
    display: flex;
    justify-content: center; /*水平居中*/
    align-items: center;  /*垂直居中*/
}

2. transform

.content{
    width: 400px;
    height: 300px;
    border: 1px solid #000;
    position: relative;
}
.box{
    width: 200px;
    height: 100px;
    background-color: darkcyan;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%)
}

3. margin

.content{
    width: 400px;
    height: 300px;
    border: 1px solid #000;
    position: relative;
}
.box{
    width: 200px;
    height: 100px;
    background-color: darkcyan;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -50px;
    margin-left: -100px;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值