css实现文字或者div盒子水平垂直居中的方法

您所在的位置:网站首页 网页设计水平垂直居中 css实现文字或者div盒子水平垂直居中的方法

css实现文字或者div盒子水平垂直居中的方法

2024-07-09 15:04| 来源: 网络整理| 查看: 265

实现水平垂直居中的方法

文本(文字)内容属于行内元素

行内元素水平垂直居中方法 方式一:

设置文字外层的盒子

text-align:center /*水平居中*/ height = 100px; /*垂直居中 */ line-height = 100px;

垂直居中只要保证行高和盒子高度一致即可 代码如下:

行高居中 .box{ width: 200px; height: 200px; text-align:center; background-color: red; line-height: 200px; } hello 方式二:转换成单元格

将文字所在的盒子display设置成table-cell

text-align:center 水平居中 display:table-cell; 垂直居中 vertical-align:middle;

注意:只有单元格元素才拥有vertical-align属性 代码如下:

垂直居中 .box{ width: 200px; height: 200px; text-align:center; background-color: red; display: table-cell; vertical-align: middle; } /*附:单元格居中方法*/ td{ width: 200px; height: 200px; background-color: green; text-align: center; } hello 123 块级元素水平居中方法

margin:0 auto; 只能设置水平居中,而margin:auto 0 不能设置垂直居中,因为margin垂直塌陷问题

方法一:定位+margin

父级元素设置position:relative; 儿子元素设置

width: 100px; height: 100px; position:absolute; top:50%; left:50%; margin-top:-50px; margin-right:-50px;

只要margin-left为高度的一半,margin-right为宽度的一半即可 代码如下:

定位和margin法盒子居中 .one{ width: 200px; height: 200px; background-color: red; position: relative; } .two{ width: 100px; height: 100px; background-color: green; /*给这个盒子定位水平垂直居中*/ position: absolute; top: 50%; left: 50%; margin-top: -50px; margin-left: -50px; /*设置盒子内文字水平,垂直居中*/ text-align:center; line-height: 100px; } 你好 方式二:定位方法

父级元素设置position:relative; 儿子元素设置

position:absolute; top:0; bottom:0; left:0; right:0; margin:auto;

这样设置以后,浏览器将自动将上下外边距相同,左右外边距相同,达到垂直居中的效果 代码如下:

纯定位法盒子居中 .big{ width: 200px; height: 200px; background-color: red; position: relative; } .small{ width: 50px; height: 50px; background-color: green; position: absolute; margin:auto; top: 0; bottom: 0; left: 0; right: 0; } 方式三:单元格方法

利用单元格法 父级元素

display:table-cell; text-align:center; vertical-align:middle;

子元素 display:inline-table 因为text-align只对行内元素和行内块生效 代码如下:

单元格法盒子居中 td{ width: 200px; height: 200px; background-color: red; text-align: center; vertical-align: middle; } span{ display: inline-block; width: 50px; height: 50px; line-height: 50px; background-color: yellow; } div.big{ width: 200px; height: 200px; background-color:purple; display: table-cell; vertical-align: middle; text-align: center; } div.small{ width: 50px; height: 50px; line-height: 50px; display: inline-block; background-color: yellow; } 小盒子 123


【本文地址】


今日新闻


推荐新闻


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