CSS中各种居中的问题

1.元素水平居中

1.在父元素上使用text-align: center;

father {
    text-align: center;  
}

2.margin: 0 auto;

在上一个问题中,我们说过,块级元素的特性是自动在宽度上填充父元素,有内容的地方自然是内容,而其余的地方使用margin填充。因此我们可以利用左右相等的margin来使元素居中。

<style type="text/css">
        #container {
            height: 100px;
            background: gray;
        }
        #testDiv1{
            height: 100px;
            margin: 0 auto;
            width: 100px;
            background: black;
        }
</style>
<body>
    <div id="container">
        <div id="testDiv1"></div>
    </div>
</body>

3.多个块级元素在一行内居中

众所周知,行级元素不能设置宽高,只能根据内容决定大小,那么想让多个块级矩形居中要怎么做呢?

块级元素独占一行,要怎么才能不独占呢?

可以设置成行内块级 inline-block,然后父元素给text-align:center

<style type="text/css">
        #container {
            text-align: center;
            height: 100px;
            background: gray;
        }
        .mydiv{
            display: inline-block;
            width: 100px;
            height: 100px;
            background: red;
        }
</style>
<body>
    <div id="container">
        <div class="mydiv"></div>
        <div class="mydiv"></div>
        <div class="mydiv"></div>
    </div>
</body>

猜你喜欢

转载自www.cnblogs.com/liwenchi/p/10675677.html