div局中

div居中的几种方法

使div水平垂直居中

1、flex布局实现(已知元素宽度)

给父盒子设置:
display: flex;
justify-content: center;
align-items: center;

2、position(已知元素宽度)

父元素设置为:position: relative;
子元素设置为:position: absolute;
距上50%,据左50%,然后减去元素自身宽度的一半距离就可以实现

3、position + transform (未知宽度)

父元素设置为:position: relative;
子元素设置为:position: absolute;
距上50%,据左50%,然后使用transform: translate(-50%,-50%);

4、position(元素已知宽度)

父元素设置为:position: relative;
子元素设置为:position: absolute;
left、right、bottom、top都为0,margin: auto;

如果子元素不设置宽度和高度,将会铺满整个父级(模态框)

5. table-cell 布局实现

table 实现垂直居中,子集元素可以是块元素,也可以不是块元素

使内容(文字,图片)水平垂直居中(table-cell 布局)

行元素 text-align :center;

块元素 :margin :0 auto;
text-align : center 给元素的父级加,可以使文本或者行级元素(例如:图片)水平居中
line-height : 值为元素的高度,可以使元素的文本内容垂直居中
margin: 0 auto 使用条件:父级元素宽度可有可无,子级元素必须使块元素,而且要有宽度(否则继承父级)

display:table-cell 会使元素表现的类似一个表格中的单元格td,利用这个特性可以实现文字的垂直居中效果。同时它也会破坏一些 CSS 属性,使用 table-cell 时最好不要与 float 以及 position: absolute 一起使用,设置了 table-cell 的元素对高度和宽度高度敏感,对margin值无反应,可以响 padding 的设置,表现几乎类似一个 td 元素。


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!