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(实现简单,缺点是兼容性不好)

扫描二维码关注公众号,回复: 6293499 查看本文章
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

猜你喜欢

转载自www.cnblogs.com/caoxueying2018/p/10937987.html