关于css:CSS水平垂直居中

12次阅读

共计 1576 个字符,预计需要花费 4 分钟才能阅读完成。

要论在前端面试中 CSS 常考的题目,程度垂直居中肯定有姓名。如果是平时不留神写款式的初学者,这道看似简略的问题也不是很容易答复,现整顿了一下 CSS 程度垂直居中的办法,可作为前端面试筹备材料。
要想做程度垂直居中,咱们先筹备两个盒子,大盒子外面套一个小盒子,这个时候咱们要想,套在外面的要做程度垂直居中的小盒子的宽高咱们晓得吗?宽高晓得或者不晓得,做程度垂直居中的办法一样吗?答案是不一样的,上面就要分状况探讨了,各提供了两种解决方案。

〇、先筹备一下盒子,也就是 html 的内容:
    <div id="father1">
        <div id="son1">
            程度垂直居中块级元素 (已知宽高)
        </div>
    </div>
    <div id="father2">
        <div id="son2">
            程度垂直居中块级元素 (已知宽高)
        </div>
    </div>
    <div id="father3">
        <div id="son3">
            程度垂直居中块级元素 (未知宽高)
        </div>
    </div>
    <div id="father4">
        <div id="son4">
            程度垂直居中块级元素 (未知宽高)
        </div>
    </div>
一、已知小盒子宽高
办法 1:子绝父相。子盒子的 top、bottom、left、right 为 0,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;
        }

办法 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;
        }

二、未知小盒子宽高
办法 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;
        }

办法 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;}

【作者程度无限,欢送大家在评论区交换斧正~】

正文完
 0