css居中的几种方式

html-css014

css居中的几种方式,第1张

1.横向居中

(1)方法一

position: fixed

/* 居中对齐begin */

left: 50%

/* 兼容老版本的方法 */

-webkit-transform: translateX(-50%)

transform: translateX(-50%)

(2)方法二

设置固定宽度,并且设置margin:auto

(3)方法三

position: fixed

left: 50% - 居中盒子宽度的50%

2.纵向居中

(1) 高度和行高设置一样

height: 100px

line-height:100px

3.横向和纵向都居中

display: flex

/* 默认的主轴是x轴row, justify-content: center 沿着主轴居中对齐 */

justify-content: center

/* 我们需要一个侧轴居中 */

align-items: center

通常首选方法是使用 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: