css居中(自己常用的)

水平居中:

1.text-aligin:center  

如果仅使用 text-aligin:center   是无法达到水平居中的效果的,为什么?

text-aligin:center  需要在行内块元素上使用的,而盒子是块级元素,所以,需要将盒子转换为行内块元素 text-aligin:center  才能生效。

<div style="text-align: center;">

  <div style="display: inline-block;"></div>

</div>

2. display:flex

<div style="display: flex;justify-content: center;">

  <div></div>

</div>

3.position(子元素绝对定位,父元素相对定位)  ,由于子元素有width属性,所以left:50%会导致子元素往右偏,因此需要往左 半个子元素 的宽度 

<div style="position: relative;">

  <div style="position: absolute; left: 50%; margin-left: -100px;"></div>  

</div>

4.margin-auto

<div style="overflow: hidden">

  <div style="margin: auto;"></div>  

</div>

 参考https://blog.csdn.net/qq_53985958/article/details/125510763

 

垂直居中:

1.table-cell

<div style="display: table-cell;vertical-align: middle;">

  <div></div>

</div>

2.display:flex

<div style="display: flex;align-items:Center;">

  <div></div>

</div>

3. position 子绝对 父相对(与上面一样,要负子元素宽度的一半)

<div style="position:relative;">

  <div style="position: absolute;margin-top:-25px;top:50%"></div>

</div>

参考https://m.php.cn/faq/473645.html

posted @ 2023-06-27 16:25  妞妞猪  阅读(66)  评论(1)    收藏  举报