常见水平垂直居中问题

常见居中问题

在编写HTML和CSS时会遇到许多元素水平、垂直居中的问题。这里,总结了一些网上看到的各种各样的解决方案,方便以后查阅,也希望更多的人可以学习。

一、文字水平居中

//适用于文字、链接、inline、inline-block、inline-table和inline-flex的元素。
#outer{
    text-align:center;
}

二、块级元素水平居中

#inner{
    margin: 0px auto;
}

三、多个块级元素水平居中

1、text-align 和 display

#outer{
    text-align:center;
}
#inner{
    display:inline-block;
}

2、flexbox实现(默认块级元素)

#outer{
    display:flex;
    /* 按照主轴中心的位置对齐 */
    justify-content:center;
}

四、未知宽高行内块元素(input , img)水平垂直居中

.outerBox{
    float: left;
    width: 300px;
    height: 300px;
    background-color: black;

    /*核心*/  
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}
.innerImg{
    width: 100px;
    height: 80px;
    background-color: white;
}

五、div(块级元素)水平垂直居中

1、需要知道宽高,top,left设为 50% 在用margin拉回宽高的一半。

.outer1{
    float: left;
    width: 300px;
    height: 300px;
    background-color: greenyellow;  

    /*核心*/          
    position: relative;   
}
.inner1{
    width: 100px;
    height: 80px;
    background-color: palevioletred;

    /*核心*/  
    position: absolute;
    top: 50%;
    left: 50%;
    margin: -40px 0 0 -50px;
}

2、未知宽高,绝对定位+margin(好用)

.outer2{
    float: left;
    width: 300px;
    height: 300px;
    background-color: plum; 

    /*核心*/          
    position: relative;
}
.inner2{
    width: 100px;
    height: 80px;
    background-color: cornflowerblue;

    /*核心*/  
    position: absolute;
    margin: auto;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
}

3、未知宽高,transform实现

.outer3{
    float: left;
    width: 300px;
    height: 300px;
    background-color: purple;

    /*核心*/              
    position: relative;
}
.inner3{
    width: 100px;
    height: 80px;
    background-color: cornflowerblue;

    /*核心*/  
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50% , -50%);
}

4、flex布局实现

#container{
    display:flex;
    /* 按照主轴中心的位置对齐 */
    justify-content:center;
    /* 交叉轴水平位置对齐 */
    align-items: center;
}

总结

transform和flexbox需要考虑兼容问题
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值