html让控件垂直,css中实现元素垂直且水平居中的六种方法

在网页制作的过程中,经常会遇到子元素嵌套在父元素中,需要子元素垂直水平居中的场景。现将子元素水平且垂直居中的几种方法总结如下:

原始代码:

*{margin:0;padding:0;}

.out_box{width:200px;height:200px;background:#99f;}

.in_box{width:100px;height:100px;background:#ff9;}

add640af75bc

pic1.原始图

add640af75bc

pic2.实现图

一.使用margin自适应和偏移实现

.out_box{

width:300px;height:300px;background:#99f;

overflow:hidden;  /*解决margin-top向上传递*/

}

.in_box{

width:200px;height:200px;background:#ff9;

margin:0 auto;  /*水平居中*/

margin-top:50px;  /*垂重居中*/

}

缺点:需要已知父元素的高度,且需要计算,当父元素高度变化的时候,需要重现计算。而且容易出现margin-top向上传递的问题,需要在父元素写overflow:hidden。

二.使用定位和margin自适应实现

.out_box{

width:300px;height:300px;background:#99f;

position:relative;  /*父元素相对定位*/

}

.in_box{

width:200px;height:200px;background:#ff9;

margin:auto;  /*水平居中*/

position:absolute;  /*子元素绝对定位*/

left:0;

right:0;

top:0;

bottom:0;

}

三.使用定位和margin固定偏移实现

.out_box{

width:300px;height:300px;background:#99f;

position:relative;

}

.in_box{

width:200px;height:200px;background:#ff9;

position:absolute;

left:50%;/*这里指的是父元素的50% */

top:50%;

margin:-100px 0 0 -100px;/* -子元素高的一半 0 0 -子元素宽的一半*/

}

四.使用定位和2D位移实现

.out_box{

width:200px;height:200px;background:#99f;

position:relative;

}

.in_box{

width:100px;height:100px;background:#ff9;

position:absolute;

left:50%;

top:50%;

transform:translate(-50%,-50%); /*这里指的是子元素的50% */

}

五.使用弹性盒子实现

.out_box{width:300px;height:300px;background:#99f;

display:flex;

justify-content:center; /*水平居中*/

align-items:center; /*垂直居中*/

}

.in_box{width:200px;height:200px;background:#ff9;}

六.使用伪元素和vertical-align实现

.out_box{

width:300px;height:300px;background:#99f;

text-align:center;/*使块元素中的行内块元素水平居中*/

font-size:0;/*去除因为子元素换行产生的右边的5px距离*/

}

.out_box:after{

content:"";

display:inline-block;/*使新建的伪元素和子元素保持在一行,且可以设置宽高*/

height:100%;/*使伪元素高度等于父元素*/

vertical-align:middle;  /*设置基线为中间*/

}

.in_box{width:200px;height:200px;background:#ff9;

display:inline-block;/*作用是不换行,且当父元素设置text-align:center时,子元素(行内块)水平对齐*/

vertical-align:middle;/*使得基线和伪元素基线对齐*/

}

以上是对css中元素垂直且水平居中的整理,如有修改、补充,后续会更新。

文中如果纰漏,错误,不合理,描述不清晰,不准确等问题,欢迎大家留言指正...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值