div在父元素内上下左右居中


(1)宽度和高度已知的

  

     .box {
            width: 400px;
            height: 200px;
            position: relative;
            background: red;
        }
        .content {
            width: 200px;
            height: 100px;
            position: absolute;
            top: 50%;
            left: 50%;
            margin-left: -100px;
            margin-top: -50px;
            background: green;
        }
    </style>

    <div class="box">
        <div class="content"></div>
    </div>

(2)宽度和高度未知

  

     <style>
        .box {
            width: 400px;
            height: 200px;
            position: relative;
            background: red;
        }
        .content {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: green;
        }
    </style>

    <div class="box">
        <div class="content"></div>
    </div>

(3)flex布局

  

    <style>
        .box {
            width: 400px;
            height: 200px;
            background: red;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .content {
            width: 200px;
            height: 100px;
            background: green;
        }
    </style>
    <div class="box">
        <div class="content"></div>
    </div>

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM