关于居中问题的小总结

水平居中:

      行元素:text-align:center;----对于图片,文字等文本属性

      块元素:①在设置了width的前提下,margin:0 auto;

              ②设置元素的display:inline-block;然后再text-align:center;

垂直方向:

      行元素(对于图片和一些小文字[display:inline-block]):vertical-align:middle;(ps:慎重使用,有时会不准确)

      块元素:可根据下面的情况自行选择

结合position和margin实现水平垂直居中:

       ①top:0; right:0;  bottom:0;  left:0; margin:auto;

       ②top:50%;left:50%;margin:-height 0 0 -width;(width 和height 是元素的宽高);

结合position和transform实现水平垂直居中:

       top:50%;left:50%;transform:translate(-50%;-50%);

           ps:translate接受两种参数:数值和百分比,其中百分比是相对于自身而言

结合table实现水平垂直居中:

       ①display:table

       ②display:table-row;

最后还有一种方法,就是可以用盒子解决(这里用新盒子示范)

①水平居中:

    

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        .father{
            display: flex;
            justify-content: center;
            width: 500px;
            height: 500px;
            background:pink;
            margin:30px auto;
        }
        .son{
            background: deeppink;
        }
    </style>
</head>
<body>
<div class="father">
    <div class="son">
            这是子模块
    </div>
</div>
</body>
</html>

 

效果为:

②垂直居中:

CSS部分代码为:

 .father{
            display: flex;
            flex-direction: column;
            justify-content: center;
            width: 500px;
            height: 300px;
            background:pink;
            margin:30px auto;
        }
        .son{
            background: deeppink;
        }

效果图为:

另一种方法:

将父元素中的CSS代码

  flex-direction: column;
            justify-content: center;

改为:

  align-items: center;

而效果为:(子元素失去占一行的权利)

如果同时设置,则会实现水平垂直居中:

  display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;

效果:

 

posted @ 2017-03-03 23:02  爱小五  阅读(92)  评论(0)    收藏  举报