CSS 基础知识之垂直水平居中

最近想转行前端 面试时被教育了 ,关于css设置水平垂直居中这个应该是基础的基础了 回答不上来确实还是有点尴尬的 我第一时间就想到了 最简单的 针对 div设置 margin 0 auto ; 实操一下 


<body>
    <div class="box">
        <div class="item">居中</div>
    </div>

</body>
<style>
    .box{
        background-color: aquamarine;
        width: 300px;
        height: 300px;
    }
    .item{
        width: 100px;
        height: 100px;
        margin: 0 auto;
        background-color: bisque;
    }
</style>

以上代码运行后可以看到 只进行了水平居中,

如果要继续达成垂直水平居中  可以在这个基础上设置相对定位 top 50% 并向上偏移元素一半的高度 代码如下  注意因为父元素是个div  给子元素设置margin-top时父元素会一起上移 所以需要给父元素设置一个padding-top 或者通过 下面的 translate来实现 

.box {
        width: 300px;
        height: 300px;
        padding-top: 1px;
        margin: 0;
        background-color: blue;

    }

    .item {
        width: 100px;
        height: 100px;
        background: orange;
        margin: 0 auto;
        /*水平居中*/
        position: relative;
        /*设置position*/
        top: 50%;
        margin-top: -50px;/*元素高度的一半 */

    }

效果如图

 

还有其他方法 比如 使用绝对定位方式来实现垂直水平居中 

<body>
    <div class="box">
        <div class="item">居中</div>
    </div>

</body>
<style>
    .box {
        background-color: aquamarine;
        width: 300px;
        height: 300px;
        position: relative;
    }

    .item {
        position: absolute;
        background-color: blanchedalmond;
        text-align: center;
        width: 100px;
        height: 100px;
        top: 50%;
        left: 50%;
        margin-top: -50px;
        /*高度的一半*/
        margin-left: -50px;
        /*宽度的一半*/
    }
</style>

 

效果如图,但是就像代码里写的一样 这种需要提前知道具体元素大小 然后通过搜索引擎看到 现在css3.0 可以使用 设置transform来替换 margin的设置 translate主要是设置元素的2d偏移量 可以针对元素自身的百分比设置 所以完成了 水平垂直居中 

  .item {
        position: absolute;
        background-color: blanchedalmond;
        text-align: center;
        width: 100px;
        height: 100px;
        top: 50%;
        left: 50%;
        transform: translate(-50%,-50%);
        /* margin-top: -50px; */
        /*高度的一半*/
        /* margin-left: -50px; */
        /*宽度的一半*/
    }

还可以使用弹性盒子 flex 布局 来实现  这个使用应该是比较多的 代码如下 

    .box {
        display: flex;
        background-color: aquamarine;
        width: 300px;
        height: 300px;
        align-items: center;
        justify-content: center;
    }

    .item {
        width: 100px;
        height: 100px;
        background: orange;
    }

  效果如下 

不知不觉就要下班了 果然实际操作一下印象还是非常深刻的 总结一下 css垂直水平居中可以通过 相对定位 绝对定位 弹性盒子 进行水平垂直居中 当然还有很多其他实现方式 这里只实际操作了这几个方法。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值