css中4种方法使内容居中

html-css011

css中4种方法使内容居中,第1张

通常首选方法是使用 flexbox 居中内容。只需三行代码即可: display:flex ,然后使用 align-items:center 和 justify-content:center 将子元素垂直和水平居中。

如下代码:

html:

css:

使用grid(网格)与flexbox非常相似,也是一种常见的技术,尤其是布局中已经使用网格的情况下。与前一种flexbox技术的唯一区别是它显示为栅格。

如下代码:

html:

css:

使用css transform 居中元素,前提是容器元素必须设置为 position:relative ,然后子元素使用 left:50%和 top:50% 偏移子元素,最后使用 translate(-50%,-50%) 以抵消其偏移的位置。

代码如下:

html:

css:

最后,表格居中是一种旧技术,在使用旧浏览器时,您可能会喜欢这种技术。前提是容器元素设置为 display:table ,然后子元素设置为 display: table-cell ,最后使用 text-align: center 水平居住和 vertical-align: middle 垂直居中。

代码如下:

html:

css:

水平居中

若是行内元素, 给其父元素设置 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}

前言:根据最近学习的课程,简单总结一下学习到的css左右布局以及居中方案。后期学习深入之后再回来进行css居中的完整总结。

给所有子元素添加 float: left ,给父元素加 clearfix 类,清除浮动

html:

css:

将内联元素外部的块级元素的 text-align 设置为 center ,即可实现内联元素( inline 、 inline-block )的水平居中。

演示

将固定宽度的块级元素的 margin-left 和 margin-right 设置为 auto ,即可实现块级元素的水平居中。

演示

将每个块级元素的 display 设置为 inline-block ,然后将它们的父容器的 text-align 设置为 center ,即可使多个块级元素水平居中。

演示

设置内联元素的行高( line-heigt )和内联元素的父元素的高度( height )相等,且内联元素的字体大小远小于行高,即可使内联元素垂直居中。

演示

通过绝对定位元素距离顶部50%,并设置margin-top向上偏移元素高度的一半,即可实现垂直居中。

演示

借助CSS3中的transform属性向Y轴反向偏移50%的方法实现垂直居中

演示