前端开发常用css居中布局

在前端开发中,经常会碰到布局需要左右居中,上下居中的情况,在现代浏览器中实现居中还是挺方便的,本文只考虑在高版本现代浏览器中的情况,不考虑IE.

1.文本居中属性 text-align

这是常用的水平居中图片,按钮,文字等行内元素的方法,但不能上下居中

<style lang="css">
    .parent {
        width: 100%;
        height: 800px;
        background: green;
    }
    
    .sub {
        width: 200px;
        height: 200px;
        background: red;
        text-align: center;
    }
</style>

<body>
    <div class="parent">
        <div class="sub">
            abcedd
        </div>
    </div>
</body>

实现效果:
此处输入图片的描述

2.自动居中 margin:auto

此方法也只能实现水平居中,具体用法为:margin:0 auto
    .sub {
        width: 200px;
        height: 200px;
        background: red;
        margin: 0 auto;
    }

实现效果:
此处输入图片的描述

3. 用line-height实现文字上下居中

    .sub {
        width: 200px;
        height: 200px;
        background: #ccc;
        margin: 0 auto;
        line-height: 200px;
        text-align: center;
    }

此处输入图片的描述

4.表格居中

如果使用表格居中的话,用表格属性 td(也可能会用到 th)元素的 align="center" 以及 valign="middle" 就可以实现左右上下居中了

5.使用display:table-cell来居中

对于不是表格的元素,可以使用display:table-cell模拟表格,实现居中的目的。这种情况下,父级容器要指定宽度,用百分比的话达不到左右居中的目的

此处输入图片的描述

<style lang="css">
    .parent {
        width: 800px;
        height: 800px;
        display: table-cell;
        vertical-align: middle;
    }
    
    .sub {
        width: 200px;
        height: 200px;
        margin: 0 auto;
        background: #ccc;
    }
</style>

<body>
    <div class="parent">
        <div class="sub">
        </div>
    </div>
</body>

6.使用定位position

<style lang="css">
    .parent {
        width: 800px;
        height: 800px;
        position: relative;
    }
    
    .sub {
        width: 200px;
        height: 200px;
        background: #ccc;
        position: absolute;
        top: 0;
        left: 0;
        bottom: 0;
        right: 0;
        margin: auto;
    }
</style>
    <div class="parent">
        <div class="sub">
        </div>
    </div>

要注意的是。margin:auto必不可少,这是其一,还有一种

<style lang="css">
    .parent {
        width: 100%;
        height: 800px;
        position: relative;
    }
    
    .sub {
        width: 200px;
        height: 200px;
        background: #ccc;
        position: absolute;
        left: 50%;
        top: 50%;
        margin-left: -100px;
        margin-top: -100px;
    }
</style>

<body>
    <div class="parent">
        <div class="sub">
        </div>
    </div>
</body>

这些都是常用的居中方式,在css3中,还可以使用弹性布局来居中元素,下篇文章在详细说明。

转自:http://dawns.me/2017/07/04/ht...

猜你喜欢

转载自www.cnblogs.com/homehtml/p/12220956.html