1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > CSS02_设置盒子水平+垂直居中 设置文本水平+垂直居中

CSS02_设置盒子水平+垂直居中 设置文本水平+垂直居中

时间:2022-03-25 15:12:18

相关推荐

CSS02_设置盒子水平+垂直居中  设置文本水平+垂直居中

写在前面:此贴为CSS高频题,针对盒子模型的水平+垂直居中,还提到了其内部文字的居中,如有补充,请留下评论

HTML代码结构:

<body><div class="box-warpper"><div class="box"></div></div></body><style>/* CSS预设,提前将不相关的基本样式写在这里,为了使得后面代码更清晰*/*{margin: 0;padding: 0;box-sizing: border-box;}html, body {height: 100%;background-color: #ccc;}.box-warpper {height: 100%;border: 2px solid green;}.box-warpper .box {width: 200px;height: 200px;background-color: red;}</style>

一、设置盒子水平 + 垂直居中

法1 - flex布局(最简单)

父元素开启flex定位,并使用justify-contentalign-items

.box-warpper {display: flex;justify-content: center;align-items: center;}

法2 - absloute 绝对定位(含两种定位方式)

子绝父相 +top | right+transform子绝父相 +top | right | bottom | left+margin:auto

/*其他基本样式上面已写,这里只写定位相关代码,后续不再赘述*/ .box-warpper {position: relative;}.box-warpper .box {position: absolute;/* 定位方式 1 */top: 50%;left: 50%;transform: translate(-50%, -50%);/* 定位方式 2 */right: 0;left: 0;top: 0;bottom: 0;margin: auto; /*必须有auto,否则不生效*/}

效果:

法3. 栅格布局 grid

父元素加入栅格, 子元素margin: auto

.box-warpper {display: grid;}.box-warpper .box {/* margin: 0 auto; 水平居中*//* margin: auto 0; 垂直居中*/margin: auto; /*水平+垂直居中*/}

法4. table-cell布局(不常用)

父元素必须设置宽高,不能用百分比。父元素设置table-cell布局,文本水平居中,垂直居中子元素设置margin:auto

.box-warpper {width: 500px;height: 500px;display: table-cell;text-align: center;vertical-align: middle;}.box-warpper .box {margin: auto;}

二、设置盒子内文本水平 + 垂直居中

HTML结构:

<body><div class="box"><span>我是单行文本</span></div></body>

1. 文本水平居中

让div中文字水平居中:text-align: center;即可

2. 文本垂直居中

2.1 单行文本垂直居中

如果一个容器中只有一行文字,对它实现居中相对比较简单,我们只需要

设置它的实际高度height和所在行的高度line-height相等即可

.box{height: 100px;line-height: 100px;}

2.2 多行文本固定高度的居中

CSS中的确是有vertical-align属性,但是它只对HTML元素中拥有valign特性的元素才生效,例如表格元素中的"td"、“th”、“caption"等,而像"div”、"span"这样的元素是没有valign特性的,因此使用vertical-align对它们不起作用。

但是在CSS中还有一个display:table,所以我们可以使用这个属性来让"div"模拟"table"就可以使用vertical-align了。注意,display:tabledisplay:table-cell的使用方法,前者必须设置在父元素上,后者必须设置在子元素上。

.box{/* 子元素相关信息 */width: 100%;height: 100%;background-color: red;/* 设置定位相关 */display: table;span{text-align: center;display: table-cell;vertical-align: middle;}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。