CSS实现水平垂直居中

不为别的,就是为了能信手拈来,所以整理了一份相关内容。

水平居中

  1. 如果水平居中元素为行内元素,设置父元素 text-align:center;
  2. 如果水平居中元素为块级固定,则需设置margin: 0 auto;(IE6下需在父元素上设置text-align: center;,再给子元素恢复需要的值)
<body>
    <div class="content">
        测试数据 测试数据 测试数据
        测试数据 测试数据 测试数据
        测试数据 测试数据 测试数据
        测试数据 测试数据 测试数据...
    </div>
</body>

<style>
    body {
        background: #DDD;
        text-align: center; 
    }
    .content {
        width: 500px;  
        text-align: left; 
        margin: 0 auto;  
        background: orange;
    }
</style>
  1. 如果元素为绝对定位,法一:设置父元素position为relative,元素设left:0;right:0;margin:auto;
body{ 
    background: #DDD;
}
.content{ 
    width: 500px;   
    background: orange;
    position: absolute;
    left: 0;
    right: 0;
    margin:0 auto;
}

法二:设置父元素position为relative,子元素设置left和负值的margin-left;

body { 
    background: #DDD;
}
.content { 
    width: 500px; 
    background: orange;
    position: absolute;
    left: 50%;
    margin-left: -250px;
}
  1. 如果元素为浮动,该元素设置position: relative, 并且浮动方向偏移量(left或者right)设置为50%,浮动方向上的margin设置为元素宽度一半乘以-1
body{ 
    background: #DDD;
}
.content{ 
    width: 500px;   
    background: orange;
    float: left;
    position: relative;
    left: 50%;
    margin-left: -250px;
}
  1. 使用flex-box布局,父元素指定justify-content属性为center;
body { 
    justify-content: center;
    display: flex;
}
.content { 
    width: 500px;
}

垂直居中

  1. 若元素为单行:可设置line-height;
  2. 若元素是行内块级元素,display: inline-block, vertical-align: middle和一个伪元素让内容块处于容器中央(注:该方法指针对不折行的子元素)。
body::after, .content{
    display: inline-block;
    vertical-align: middle;
}
body::after{
    content: '';
    height: 100%;
}
body {
    height: 200px;
}
  1. 将显示方式设置为表格,display:table-cell,同时设置vertial-align:middle;
body {
    display: table;
    width: 100%;
    height: 200px;
}

.content {
    display: table-cell;
    vertical-align: middle;
    border: 1px solid #666;
}
  1. 使用flex布局,设置为align-item:center;
body {
    display: flex;
    align-items: center;
    width: 100%;
    height: 200px;
    border: 1px solid #666;
}
  1. 如果元素为绝对定位,法一:子元素中设置bottom:0,top:0,并设置margin:auto;
body { 
    background: #DDD;
}
.content { 
    width: 500px;
    height: 200px;  
    background: orange;
    position: absolute;
    bottom: 0;
    top: 0;
    margin: auto 0;
}

法二:子元素设置top:50%,margin-top值为高度一半的负值;

body { 
    background: #DDD;
}
.content { 
    width: 500px; 
    height: 200px;
    background: orange;
    position: absolute;
    top: 50%;
    margin-top: -100px;
}

参考:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值