博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
html让控件垂直,css中实现元素垂直且水平居中的六种方法
阅读量:4318 次
发布时间:2019-06-06

本文共 1964 字,大约阅读时间需要 6 分钟。

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

原始代码:

*{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中元素垂直且水平居中的整理,如有修改、补充,后续会更新。

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

转载地址:http://nkgzs.baihongyu.com/

你可能感兴趣的文章
在所选中的物体中取消选中一些物体.txt
查看>>
grid - 网格项目跨行或跨列
查看>>
Shell 基本运算符
查看>>
2019年2月
查看>>
Google Noto Sans CJK 字体
查看>>
ES集群性能调优链接汇总
查看>>
STL库的应用
查看>>
spark算子
查看>>
(转)Linux服务器SNMP常用OID
查看>>
经典机器学习算法系列7-svd
查看>>
USB各种模式 解释
查看>>
数据访问-----ADO.NET 小结和练习
查看>>
Linux lsof详解
查看>>
子组件给父组件传数据
查看>>
unix/linux下的共享内存、信号量、队列信息管理
查看>>
Hilbert先生旅馆的故事
查看>>
[家里蹲大学数学杂志]第394期分组求积分因子法
查看>>
[唐诗]送杜少府之任蜀州-王勃
查看>>
华中科技大学数学专业考研试题参考解答
查看>>
Objective-C数组初识
查看>>