垂直水平居中方法总结

今天老大随口问了这个问烂了的问题,我只回答了两种,好吧,还是老老实实总结下来加强下记忆吧。


一:定位+边距(固定宽高度适用)

<div class="container">
    <div class="inner"></div>
</div>
复制代码
.container {
    width: 400px;
    height: 400px;
    position: relative;
    background-color: yellow;
}

.inner {
    position: absolute;
    height: 200px;
    width: 200px;
    left: 50%;
    top: 50%;
    margin-left: -100px;
    margin-top: -100px;
    background-color: red;
}
复制代码

二:定位+transform(不固定宽高也适用)

.container {
    width: 400px;
    height: 400px;
    background-color: yellow;
    position: relative;
}

.inner {
    height: 200px;
    width: 200px;
    background-color: red;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}
复制代码

三:flex布局

.container {
    width: 400px;
    height: 400px;
    background-color: yellow;
    display: flex;
    align-items: center;
    justify-content: center;
}

.inner {
    height: 200px;
    width: 200px;
    background-color: red;
}
复制代码

四:table布局

 <div class="container">
    <div class="outter">
        <div class="inner"></div>
    </div>
</div>
复制代码
.container {
    width: 400px;
    height: 400px;
    background-color: yellow;
    display: table;
}

.outter {
    background-color: red;
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}

.inner {
    height: 100px;
    width: 100px;
    display: inline-block;
    background-color: white;
}
复制代码

五:杂谈

以上为比较好用的块级元素居中方案,别的一些细节如下:

行内元素垂直居中:

1、父元素等值padding

2、子元素line-height等于父元素高度

块级元素水平居中:

margin: 0 auto
复制代码

基础还是要打好的,知道不行,熟练也不够,希望刻在脑子里,形成条件反射才足够。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值