每天一个html小知识【水平垂直居中】

278 阅读2分钟

每天一个html小知识【水平垂直居中】

大家好,我是怀恋,很高兴和大家分享这一遍文章。写这篇文章的目的是用来记录自己前端的学习情况,也为自己马上面临的秋招做好准备。文笔不好,多多包涵。

在平时的项目开发中,一个排列整洁的页面是不可或缺的,在页面布局中我们常常会用到水平垂直的方法来使页面布局更加美观,下面我就介绍几种比较常用的元素水平垂直居中的方法。


1.弹性布局(flex)

利用flex弹性布局,只需要在父元素内设置代码即可。
  <style>
#father{
    height: 500px;
    display: flex;
    justify-content:center; /*水平居中*/
    align-items:center;   /*垂直居中*/
    }
#son{
    width: 200px;
    height: 200px;
    background-color: black;
}

</style>

2.绝对定位+margin:auto

将父元素设置相对定位,子元素绝对定位并且将left,top,right,bottom设置为0,再设置margin:auto即可。
#father{
    height: 500px;
    position: relative;
    }
#son{
    width: 200px;
    height: 200px; 
    background-color: black;
    position:absolute;
    top:0;
    left:0;
    right:0;
    bottom:0;
    margin: auto;
}

3.绝对定位+margin(已知宽高)

该方法与上面一个方法类似,不同在于将left和top设置为50%,margin-left和margin-top分别设置为该元素宽度,高度的一半。
#father{
    height: 500px;
    position: relative;
    }
#son{
     width: 200px;
    height: 200px; 
    background-color: black; 
    position:absolute;
    top:50%;
    left:50%;
    margin-left:-100px;
    margin-top:-100px;
}

4.translate(未知宽高)

利用css提供的transform的translate(平移),使元素水平垂直居中。
 #father{
    height: 500px;
    position: relative;
    }
#son{
    position:absolute;
    left:50%;
    top:50%;
    transform: translate(-50%,-50%);
}

5.display:table-cell

display:table-cell可将元素变为表格单元格显示。
#father{
height: 500px;
width: 500px;
display: table-cell;
vertical-align: middle;
text-align: center;
}
#son{
    vertical-align: middle;
}

以上就是我知道比较常见的水平垂直居的方法啦,如果还有其他方法或者存在错误的地方欢迎在评论区留言,谢谢阅读。