巧用CSS居中未知高度的块元素

  在网页中让一个未知高度的块元素水平垂直居中是一个老生常谈的问题,但是总是有些特殊场景让你无法得心应手的实现居中,本文介绍几种常用的经典的居中方法,总有一种适合你!

1. position

.parent {
    width: 200px;
    height: 200px;
    margin: auto;
    border: 1px solid red;
    position: relative;
}
.child {
    position: absolute;
    width: 100px;
    height: 50%;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    background-color: red;
}

 

2. flex

.parent {
    width: 200px;
    height: 200px;
    margin: auto;
    border: 1px solid red;
    display: -webkit-box;
    display: -moz-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
    -webkit-box-pack: center;
    -webkit-justify-content: center;
    -ms-flex-pack: center;
    justify-content: center;
    -webkit-box-align: center;
    -webkit-align-items: center;
    -ms-flex-align: center;
    align-items: center;
}
.child {
    width: 100px;
    height: 50%;
    background-color: red;
}

 

3. translate

.parent {
    width: 200px;
    height: 200px;
    margin: auto;
    border: 1px solid red;
    position: relative;
}
.child {
    width: 100px;
    height: 50%;
    background-color: red;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}

 

4. calc

.parent {
    width: 200px;
    height: 200px;
    margin: auto;
    border: 1px solid red;
    position: relative;
}
.child {
    width: 100px;
    height: 50%;
    background-color: red;
    position: absolute;
    left: -webkit-calc(50% - 25%);
    left: -moz-calc(50% - 25%);
    left: -ms-calc(50% - 25%);
    left: calc(50% - 25%);
    top: -webkit-calc(50% - 25%);
    top: -moz-calc(50% - 25%);
    top: -mz-calc(50% - 25%);
    top: calc(50% - 25%);
}

  本文介绍的四种方法全部由以下实例验证通过,且加了兼容性前缀,可以直接复制使用,建议使用时可以按顺序考虑,具体可看个人习惯,反正我是这个顺序,因为可以少写很多兼容性前缀,大家可以放心大胆的粘贴使用了,拿贴不谢!

  布局如下:

  效果如下:

转载于:https://www.cnblogs.com/lewiscutey/p/7501974.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值