前端面试中CSS水平垂直居中的方法,你知道吗?

  要论在前端面试中CSS常考的题目,水平垂直居中一定有姓名。如果是平时不注意写样式的初学者,这道看似简单的问题也不是很容易回答,现整理了一下CSS水平垂直居中的方法,可作为前端面试准备资料。

  要想做水平垂直居中,我们先准备两个盒子,大盒子里面套一个小盒子,这个时候我们要想css设置垂直居中,套在里面的要做水平垂直居中的小盒子的宽高我们知道吗?宽高知道或者不知道,做水平垂直居中的方法一样吗?答案是不一样的,下面就要分情况讨论了,各提供了两种解决方案。

  〇、先准备一下盒子,也就是html的内容:

  

            
                水平垂直居中块级元素(已知宽高)
            
        
        
            
                水平垂直居中块级元素(已知宽高)
            
        
        
            
                水平垂直居中块级元素(未知宽高)
            
        
        
            
                水平垂直居中块级元素(未知宽高)
            

  一、已知小盒子宽高方法1:子绝父相。子盒子的top、bottom、left、right为0css设置垂直居中,margin为auto

   #father1{

                width: 600px;
                height: 300px;
                position: relative;
                background-color: aquamarine;
                margin-bottom: 10px;
            }
            #son1{
                position: absolute;
                width: 100px;
                height: 80px;
                top: 0;
                bottom: 0;
                left: 0;
                right: 0;
                margin: auto;
                background-color: beige;

  CSS-水平垂直居中

  方法2:子绝父相。子盒子的top、left为50%,margin-top为负的子盒子高度的一半,margin-left为负的子盒子宽度的一半

   #father2{

                width: 600px;
                height: 300px;
                position: relative;
                background-color: blueviolet;
                margin-bottom: 10px;
            }
            #son2{
                position: absolute;
                width: 100px;
                height: 80px;
                left: 50%;
                top: 50%;
                margin-left: -50px;   /* #son2盒子宽度的一半的负数*/
                margin-top: -40px;    /* #son2盒子高度的一半的负数*/
                background-color: chartreuse;

  CSS-水平垂直居中

  二、未知小盒子宽高方法1:子绝父相。子盒子的top、left为50% ,transform: translateX(-50%) translateY(-50%)

   #father3{

                width: 600px;
                height: 300px;
                background-color: coral;
                position: relative;
                margin-bottom: 10px;
            }
            #son3{
                position: absolute;
                left: 50%;
                top: 50%;
                transform: translateX(-50%) translateY(-50%);
                background-color: cornsilk;

  CSS-水平垂直居中

  方法2:弹性布局。设置justify-items和align-items为center

   #father4{

                width: 600px;
                height: 300px;
                display: flex;
                justify-content: center;
                align-items: center;
                background-color: darkred;
            }
            #son4{
                background-color: darkgrey;

  CSS-水平垂直居中

  【作者水平有限,欢迎大家在评论区交流指正~】

  程序员灯塔

文章由官网发布,如若转载,请注明出处:https://www.veimoz.com/1460
0 评论
381

发表评论

!
在线咨询
在线咨询
以确保在用户需要帮助时能够及时提供解答和技术支持
您好,这里是小灯泡设计,请登录后咨询。