css怎么设置居中

html-css07

css怎么设置居中,第1张

水平居中

若是行内元素, 给其父元素设置 text-align:center,即可实现行内元素水平居中.

若是块级元素, 该元素设置 margin:0 auto即可.

若子元素包含 float:left 属性, 为了让子元素水平居中, 则可让父元素宽度设置为fit-content,并且配合margin, 作如下设置:

.parent{

width: -moz-fit-content

width: -webkit-fit-content

width:fit-content

margin:0 auto}

使用flex 布局, 可以轻松的实现水平居中, 子元素设置如下:

.son{

display: flex

justify-content: center}

使用CSS3中新增的transform属性, 子元素设置如下:

.son{

position:absolute

left:50%

transform:translate(-50%,0)}

使用绝对定位方式, 以及负值的margin-left, 子元素设置如下:

.son{

position:absolute

width:固定

left:50%

margin-left:-0.5宽度}

使用绝对定位方式, 以及left:0right:0margin:0 auto子元素设置如下:

.son{

position:absolute

width:固定

left:0

right:0

margin:0 auto}

垂直居中

若元素是单行文本, 则可设置 line-height 等于父元素高度

若元素是行内块级元素, 基本思想是使用display: inline-block, vertical-align: middle和一个伪元素让内容块处于容器中央.

.parent::after, .son{

display:inline-block

vertical-align:middle}.parent::after{

content:''

height:100%}

元素高度不定

可用 vertical-align 属性, 而vertical-align只有在父层为 td 或者 th 时, 才会生效, 对于其他块级元素, 例如 div、p 等, 默认情况是不支持的. 为了使用vertical-align, 我们需要设置父元素display:table, 子元素 display:table-cellvertical-align:middle

用 Flex 布局

.parent {

display: flex

align-items: center}

可用 transform , 设置父元素相对定位(position:relative), 子元素如下css样式:

.son{

position:absolute

top:50%

-webkit-transform: translate(-50%,-50%)

-ms-transform: translate(-50%,-50%)

transform: translate(-50%,-50%)}

元素高度固定

设置父元素相对定位(position:relative), 子元素如下css样式:

.son{

position:absolute

top:50%

height:固定

margin-top:-0.5高度}

设置父元素相对定位(position:relative), 子元素如下css样式:

.son{

position:absolute

height:固定

top:0

bottom:0

margin:auto 0}

text-align: center水平居中

height:30pxline-height:30px垂直居中

vertical-align:middle垂直居中

td里面可以直接<td valign="middle" align="center"

层叠样式表(英文全称:Cascading Style Sheets)是一种用来表现HTML(标准通用标记语言的一个应用)或XML(标准通用标记语言的一个子集)等文件样式的计算机语言。CSS不仅可以静态地修饰网页,还可以配合各种脚本语言动态地对网页各元素进行格式化

CSS 能够对网页中元素位置的排版进行像素级精确控制,支持几乎所有的字体字号样式,拥有对网页对象和模型样式编辑的能力。

其实当时在互联网界已经有过一些统一样式表语言的建议了,但CSS是第一个含有“层叠”丰意的样式表语言。在CSS中,一个文件的样式可以从其他的样式表中继承。读者在有些地方可以使用他自己更喜欢的样式,在其他地方则继承或“层叠”作者的样式。这种层叠的方式使作者和读者都可以灵活地加入自己的设计,混合每个人的爱好。

哈坤于1994年在芝加哥的一次会议上第一次提出了CSS的建议,1995年的www网络会议上CSS又一次被提出,博斯演示了Argo浏览器支持CSS的例子,哈肯也展示了支持CSS的Arena浏览器。

text-align: center 只能用于行内元素的水平居中,用在块级元素或容器中是无效的

试试这样:

<div class="metro-layout horizontal" style="margin: 0 auto">