css水平居中的方法及代码

您所在的位置:网站首页 dw中的文字居中代码 css水平居中的方法及代码

css水平居中的方法及代码

#css水平居中的方法及代码| 来源: 网络整理| 查看: 265

一、水平居中 (1)行内元素

行内元素包括文本,图片,p标签等。可以通过设置父元素的text-align=center。 在这里插入图片描述

.center{ text-align: center; } 行内元素水平居中

p

a (2)元素宽度确定

当前元素的宽度是确定的时候设置当前元素的margin为auto 在这里插入图片描述

.second{ width: 100px; height: 100px; margin:auto; background-color: brown; } (3)当前元素为绝对定位

当前元素为绝对定位时,不需要有明确的宽度。可以设置父元素为相对定位,当前元素为绝对定位,且left=0,right=0,margin=auto. 在这里插入图片描述

.third{ width: 100%; height: 100px; border: solid 1px #000000; position: relative; } .thirdchild{ width: 50%; height: 100px; position: absolute; left: 0; right: 0; margin: auto; background-color: brown; } (4)采用flex box 布局

设置父元素的display属性为flex,justify-content=center; 在这里插入图片描述

.fourth{ width: 100%; height: 100px; border: solid 1px #000000; display:flex; justify-content: center; } .fourthchild{ width: 50%; height: 100px; background-color: brown; } (5)采用table cell 布局

对于不是表格的元素,可以通过 display: table-cell 将其模拟成一个表格单元格 td。设置父元素的display为table cell,并设置text-aglin=center就可以水平居中了。注意当前元素必须为行内元素,text-aglin才起作用。vertical-align: middle;垂直居中没有这一限制。 在这里插入图片描述

.fifth{ width: 200px; height: 200px; border: solid 1px #000000; display: table-cell; text-align: center; vertical-align: middle; } 表格1 表格2 表格3


【本文地址】


今日新闻


推荐新闻


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