css 不定寬高的div元素水平垂直居中


效果圖:

 

方法一:

 

此div元素應是 inline-block:

 

用一個“ghost”偽元素(看不見的偽元素)和 inline-block / vertical-align 可以搞定居中,非常巧妙。但是這個方法要求待居中的元素是 inline-block,不是一個真正通用的方案。兼容IE8.

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
    
        .block {
          text-align: center;
          background: #abcdef;
        }

        .block:before {
          content: '';
          display: inline-block;
          height: 100%;
          vertical-align: middle;
          margin-right: -0.25em; /* Adjusts for spacing */
        }

        .centered {
          display: inline-block;
          vertical-align: middle;
          width: 50%;
          border: 1px solid red;
        }

    </style>
</head>
<body>

    <div class="block" style="height: 300px;">
        <div class="centered">
            <h1>案例題目</h1>
            <p>案例內容案例內容案例內容案例內容案例內容</p>
        </div>
    </div>

</body>
</html>
View Code

 方法二:

CSS3(實現簡單,缺點是兼容性不好)

display: flex;

justify-content:center; //子元素水平居中
align-items:center; //子元素垂直居中

方法三:

此方法和我們固定高寬的差不多,但是不用margin我們用的是 translate()

貼上代碼:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>不固定高度div寫法</title>
     <style>
        .center {
          position: fixed;
          top: 50%;
          left: 50%;
          background-color: #abcdef;
          width:50%;
          height: 50%;
          transform: translateX(-50%) translateY(-50%);
        }
     </style>
</head>
<body>
    <div class="center"></div>
</body>

</html>
View Code

方法四:

運用margin:auto進行垂直居中

margin的值設置為auto,可以讓我們對剩余空間進行分配!我們知道,塊級元素設置為margin:0 auto;可以左右居中顯示!那有沒有辦法讓margin設置為margin:auto之后,上下左右都居中呢?上下左右都居中,就可以實現我們的垂直居中了!

答案是有的,只要我們讓上下有足夠的空間,就可以讓margin的auto來分配上下空間。

我們可以利用定位的方式,讓margin上下左右都有足夠的空間!那么就可以用margin:auto來實現垂直居中了!

貼上代碼:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>不固定高度div寫法</title>
     <style>
        .father{
            position:fixed;
            width:100%;
            height:100%;
            top:0;
            left:0;
            background-color:rgba(0,0,0,.7);
        }
        .son{
             position: absolute;
             top:0;
             left:0;
             bottom:0;
             right:0;
             width:50%;
             height:50%;
             margin:auto;
             background-color:red;
         }
     </style>
</head>
<body>
    <div class="father">
        <div class="son"></div>
    </div>
</body>

</html>
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM