css中4种方法使内容居中

html-css022

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:

1、定位+margin:auto 父元素 position: relative 子元素 position: absolute

left:0top:0right:0bottom:0margin: auto

2、定位+margin-left+margin-top 父元素 position: relative 子元素 position:absolute

left:50%top:50%margin-left: -当前盒子宽度的一半margin-top: -当前盒子高度的一

3、定位+transfrom(子元素未知宽高)父元素 position: relative 子元素 position:

absolute left:50%top:50%transform: translate(-50%,-50%)• 弹性盒子父元素 display:

flexjustify-content: centeralign-items: center

4、flex+margin: auto 父元素 display: flex子元素 margin:auto