水平垂直居中

<div class="father">
	<div class="son"></div>
</div>

1:margin:anto

.father {
    background-color: aquamarine;
    width: 400px;
    height: 400px;
    position: relative;
}
.son {
    background-color: brown;
    width: 200px;
    height: 200px;
    position: absolute;
    margin: auto;
    top: 0px;
    bottom: 0px;
    right: 0px;
    left: 0px;
}
  1. 负margin法
.father {
    background-color: aquamarine;
    width: 400px;
    height: 400px;
    position: relative;
}
.son {
    background-color: brown;
    width: 200px;
    height: 200px;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -100px; /* 负height的一半 */
    margin-top: -100px;  /* 负width的一半 */
}
  1. transform: translate(-50%, -50%)
.father {
    background-color: rgb(183, 201, 195);
    width: 400px;
    height: 400px;
    position: relative;
}
.son {
    background-color: rgb(233, 173, 173);
    width: 200px;
    height: 200px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
} 
  1. 弹性盒子:display:flex— CSS3的新属性

align-items:Y轴居中;justify-content:X轴居中

.father {
    background-color: rgb(183, 201, 195);
    width: 400px;
    height: 400px;
    display: flex;
    align-items: center;
    justify-content: center;
}
.son {
    background-color: rgb(233, 173, 173);
    width: 200px;
    height: 200px;
}
  1. table-cell
table-cell + text-algin
.father {
    background-color: rgb(183, 201, 195);
    width: 400px;
    height: 400px;
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}
.son {
    background-color: rgb(230, 132, 132);
    width: 200px;
    height: 200px;
    display: inline-block;
} 


table-cell + margin
.father {
    background-color: rgb(183, 201, 195);
    width: 400px;
    height: 400px;
    display: table-cell;
    vertical-align: middle;
}
.son {
    background-color: rgb(230, 132, 132);
    width: 200px;
    height: 200px;
    margin: 0 autto;
} 
  1. vertical-align: middle ---- 位于父元素的中部:可水平垂直居中文字
.father {
    background-color: rgb(183, 201, 195);
    width: 400px;
    height: 400px;
    display: table-cell;
    vertical-align: middle; 
    text-align: center;
}

<div class="father">
	<p>我是儿子</p>
</div>

版权声明:本文为chen_rong999原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。