面试官:水平垂直居中有哪些诶。

159 阅读1分钟

已知子元素高度和宽度

1. 设置top,bottom,left,right为0,margin为auto

<style>
        #father {
            width: 500px;
            height: 300px;
            background-color: skyblue;
            position: relative;
        }

        #son {
            width: 100px;
            height: 100px;
            text-align: center;
            line-height: 100px;
            font-size: 10px;
            background-color: green;
            position: absolute;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
            margin: auto;
        }
    </style>
    
    <div id="father">
        <div id="son">我是块级元素</div>
    </div>

2. 子元素设置left:50%,top:50%,margin-left为元素宽度的一半,margin-top为元素高度的一半

<style>
        #father {
            width: 500px;
            height: 300px;
            background-color: skyblue;
            position: relative;
        }

        #son {
            width: 100px;
            height: 100px;
            text-align: center;
            line-height: 100px;
            font-size: 10px;
            background-color: green;
            position: absolute;
            top: 50%;
            left: 50%;
            margin-left: -50px;
            margin-top: -50px;
        }
    </style>
    
     <div id="father">
        <div id="son">我是块级元素</div>
    </div>

未知子元素高度和宽度

1. left和top设置50%,使用transfrom:translateX(-50%);translateY(-50%)

<style>
        #father {
            width: 500px;
            height: 300px;
            background-color: skyblue;
            position: relative;
        }

        #son {
            text-align: center;
            background-color: green;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translateX(-50%) translateY(-50%);
        }
    </style>
    
     <div id="father">
        <div id="son">我是块级元素</div>
    </div>

2. 使用flex布局

<style>
        #father {
            width: 500px;
            height: 300px;
            background-color: skyblue;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        #son {
            text-align: center;
            background-color: green;
        }
    </style>
    
     <div id="father">
        <div id="son">我是块级元素</div>
    </div>

记录记录!