总结下我常用的垂直水平居中

来源:互联网 发布:冒泡排序c语言详解 编辑:程序博客网 时间:2024/06/12 21:28

总做中可能会遇到各种需要垂直水平居中的问题,这里总结下我常见的集中。

第一:利用定位position:

1.1在元素宽高已知的情况下,配合负margin达到水平居中

.parent{position:relative}

.child{position:absolute;

top:50%;

left:50%;

width:50px;height:50px:

margin:-25px;

margin-top:-25px

}


<div class="parent" style="background-color: lightgray; width:200px; height:100px; ">
  <div class="child" style="background-color: lightblue;">啦啦啦啦</div>

</div>

1.2宽高未知的情况下,利用css3的属性

.parent{position:relative}

.child{position:absolute;

top:50%;

left:50%;

width:50px;height:50px:

transform:translate(-50%,-50%)

}


<div class="parent" style="background-color: lightgray; width:200px; height:100px; ">
  <div class="child" style="background-color: lightblue;">啦啦啦啦</div>

</div>

1.3利用绝对定位元素的盒模型特性,在偏移属性为确定值的基础上,设置margin:auto

.parent{position:relative}

.child{position:absolute;

top:0; bottom:0;

left:0;right:0;

margin:auto

width:50px;height:50px:

}


<div class="parent" style="background-color: lightgray; width:200px; height:100px; ">
  <div class="child" style="background-color: lightblue;">啦啦啦啦</div>

</div>

第二:渲染成table-cell 之后vertival-align:middle

2.1

.parent{
    display: table-cell;
    text-align: center;
    vertical-align: middle;}
.child{
    display: inline-block;}

<div class="parent" style="background-color: gray; width:200px; height:100px;">
  <div class="child" style="background-color: lightblue;">测试文字</div>

</div>

2.2若若子元素是图像,可不使用table-cell,而是其父元素用行高替代高度,且字体大小设为0。子元素本身设置vertical-align:middle

.parent{
    text-align: center;
    line-height: 100px;
    font-size: 0;}
.child{
    vertical-align: middle;}

<div class="parent" style="background-color: gray; width:200px; ">

      <img class="child" src="。。。。" width="50%" alt="test">

</div>

第三弹性布局:

3.1在伸缩项目上使用margin:auto

.parent{
    display: flex;}
.child{
    margin: auto;}

<div class="parent" style="background-color: lightgray; width:200px; height:100px; ">
  <div class="child" style="background-color: lightblue;">啦啦啦啦</div>

</div>
3.2在伸缩容器上使用主轴对齐justify-content和侧轴对齐align-items
<style>
.parent{
    display: flex;
    justify-content: center;
    align-items: center;}

<div class="parent" style="background-color: lightgray; width:200px; height:100px; ">
  <div class="child" style="background-color: lightblue;">啦啦啦啦</div>

</div>

其实还有很多方法,浮动啊之类的必过没有用过

最后,单行文本垂直水平居中的话就是text-align+line-height了。


1 0