CSS居中

1. margin:0 auto;
此方法只能进行水平居中且对浮动元素和绝对定位元素无效;
对子元素进行设置。

2.text-align:center;
只能对图片,按钮,文字等行内元素(display为inline或inline-block等)进行水平居中。IE6、7能对任何元素进行设置。对父元素进行设置。

3.line-heigt对单行文字垂直居中
把文字的line-height设为文字父容器高度时内部文字处置居中。

4.display:table-cell;
对于不是表格的元素可以通过display:table-cell来模拟表格,这样可以很方便的利用表格的属性来居中。

5.使用绝对定位来居中
此方法我必须知道元素的宽度和高度。例如下面的案例:

   <div id="background">
        <div class="left-top"></div>
        <div class="right-bottom"></div>
    </div>
#background{
    background-color: #ccc;
    width: 400px;
    height: 200px;
    position: absolute;
    left:50%;
    top:50%;
	margin-left: -200px;        //是以左上角对齐的,所以减去div宽高的一半实现中心对齐
    margin-top: -100px;  
    overflow: hidden;
}

.left-top{
    width:50px;
    height: 50px;
    background-color: #fc0;
    position:absolute;
    border-radius: 0 0 50px 0;
}

.right-bottom{
    width:100px;
    height: 100px;
    background-color: #fc0;
    position:absolute;
    right:-50px;
    bottom:-50px;
    border-radius: 50px ;
}

效果:

 

div居中

task_1_4_1

 

原文地址:https://www.cnblogs.com/MandyCheng/p/8656468.html