CSS 元素居中的多种方法

本文参照此文章 元素居中的多种方法——css布局技巧,做个笔记,以便后用查询,如有侵权,联系删除

题目:元素布局,让 boxcontent 上下左右居中
<div class="content">
    <div class="box"></div>
</div>
1. 元素定位 position:absolute
.content{
    width:500px;
    height:300px;
    border:1px solid #0a3b98;
    position: relative;
}
.box{
    width:100px;
    height:40px;
    background: #f0a238;
    position: absolute;
    top:0;
    left:0;
    right:0;
    bottom:0;
    margin:auto;
}
2. CSS3 位移 translate(x, y)
.content{
    width:500px;
    height:300px;
    border:1px solid #0a3b98;
    position: relative;
}
.box{
    width:100px;
    height:40px;
    background: #f0a238;
    position: absolute;
    top:50%;
    left:50%;
    transform: translate(-50%,-50%);
}
3. 利用内联块元素 display:inline-block
.content{
    width:500px;
    height:300px;
    border:1px solid #0a3b98;
    text-align: center;
}
.content:before{
    content: '';
    height:100%;
    width:0;
    display: inline-block;
    vertical-align: middle;
    // vartical-align 这个属性只对内联元素以及内联块元素起作用
    // 这个属性有一个缺点:需要一个参照物,也就是说如果父级里面有两个子元素
    // 两个子元素都设置了vertical-align:middle,那么得到的效果只是这两个元素之间居中对齐而已
}
.box{
    width:100px;
    height:40px;
    background: #f0a238;
    display: inline-block;
    vertical-align: middle;
}
4. 弹性盒模型
.content{
    width:500px;
    height:300px;
    border:1px solid #0a3b98;
    display: flex;
    justify-content: center;
    align-items: center;
}
.box{
    width:100px;
    height:40px;
    background: #f0a238;
}
5. 网格布局 Grid
.content{
    width:500px;
    height:300px;
    border:1px solid #0a3b98;
    display: grid;
    justify-content: center;
    align-items: center;
}
.box{
    width:100px;
    height:40px;
    background: #f0a238;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值