html中盒子垂直水平居中的方式(目前总结的有六种方式,持续更新中)附有代码详解

您所在的位置:网站首页 html盒子水平居中 html中盒子垂直水平居中的方式(目前总结的有六种方式,持续更新中)附有代码详解

html中盒子垂直水平居中的方式(目前总结的有六种方式,持续更新中)附有代码详解

#html中盒子垂直水平居中的方式(目前总结的有六种方式,持续更新中)附有代码详解| 来源: 网络整理| 查看: 265

(1)用margin负边距实现带着宽度属性和高度属性的绝对定位的元素的居中。 (2)margin:auto;实现带有width属性和height属性的绝对定位元素的居中。 (3)用transform:translate(x,y) 代码展示如下: (4)用display:table-cell属性 (5)设置上下外边距的方法 (6)第六种用弹性盒子display:flex来实现子元素的垂直水平居中

Document .wrap{ height: 300px; border-bottom: 2px solid #000000; position: relative; background: wheat; } .wrap1 .box{ position: absolute; left: 50%; top: 50%; margin-left: -100px; /* -100px相当于向左移动100px */ margin-top: -50px; width: 200px; height: 100px; background: yellow; } .wrap1 .box div{ width: 100px; height: 100px; background: pink; } .wrap2 .box{ position: absolute; left: 0; top: 0; right: 0; bottom: 0; margin: auto; width: 300px; height: 200px; background: yellow; } .wrap3 .box{ position: absolute; left: 50%; top: 50%; transform: translate(-50%,-50%); } .wrap3 .box div{ width: 100px; height: 100px; background-color: yellow; } --(2)margin:auto;实现带有width属性和height属性的绝对定位元素的居中 --> --3,transform:translate()实现绝对定位元素的居中-->

用display:table-cell实现垂直水平居中的代码如下:

Document .wrap { width: 500px; height: 500px; background-color: red; display: table-cell; vertical-align: middle; text-align: center; } .box1 { width: 200px; height: 200px; display: inline-block; vertical-align: middle; background-color: yellow; }

第四种方式效果图如下: 在这里插入图片描述 下面再补充一下display:table-cell属性的特点: 来自转载:作者是:paopaolee,作者总结的display:table-cell属性较全,点击此处也可查看 display:table-cell 详解 display:table-cell属性指让标签元素以表格单元格的形式呈现,类似于td标签。目前IE8+以及其他现代浏览器都是支持此属性的,但是IE6/7只能对你说sorry了,这一事实也是大大制约了display:table-cell属性在实际项目中的应用; 单元格有一些比较特别的属性,例如元素的垂直居中对齐,关联伸缩等,设置了display:table-cell的元素对宽度高度敏感,对margin值无反应,响应padding属性,基本上就是活脱脱的一个td标签元素了。

display:table-cell与大小不固定元素的垂直居中

第五种方式简单使用:

Document .wrap { width: 600px; height: 600px; background-color: red; border: 1px solid transparent; /* 由于涉及到父子关系的外边距塌陷,所以给父盒子设置1px的透明边框来阻止塌陷 */ } .box { width: 200px; height: 200px; background-color: blue; margin: 200px auto; 父盒子高600px, 子盒子高200px, 600-200=400px, 400/2=200px,子盒子上外边距200px,下外边距200px, 所以 margin: 200px auto; 给子盒子上下外边距设置200,左右自适应,也就是居中。 }

第六种用弹性盒子display:flex来实现子元素的垂直水平居中

Document .wrap { display: flex; justify-content: center; /* justify-content: center;设置子元素位于弹性盒的中间 */ align-items: center; /* align-items: center;设置盒子在交叉轴居中 */ width: 400px; height: 400px; background-color: red; } .box { width: 200px; height: 200px; background-color: yellowgreen; }


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3