css 元素各种居中方法

①、  常用水平居中:给div设置一个宽度,宽度是必要条件,然后添加margin:0 auto属性

div{
    width:200px;
    margin:0 auto;
}

②、绝对定位居中

绝对定位使元素的位置与文档流无关,因此不占据空间。

绝对定位的元素的位置相对于最近的已定位祖先元素,如果元素没有已定位的祖先元素,那么它的位置相对于最初的包含块

水平居中:left属性和right属性的值相对即可,不一定为0

div {
    position: absolute;
    width: 300px;
    height: 300px;
    left: 0;
    right: 0;
    margin: o auto;
    background-color: pink;	
 }

垂直居中:top属性和bottom属性的值相对即可,不一定为0

div {
    position: absolute;
    width: 300px;
    height: 300px;
    top: 0;
    bottom: 0;
    margin: auto 0;
    background-color: pink;	
 }

③、外边距定位居中

left属性值为50%,则margin-left为width的一半即可(负数)

div {
    position: relative;		/* 相对定位或绝对定位均可 */
    width:500px;
    height:300px;
    top: 50%;
    left: 50%;
    margin: -150px 0 0 -250px;     	/* 外边距为自身宽高的一半 */
    background-color: pink;	 	
}

④、未知父容器的宽高,利用 `transform` 属性

div {
    position: absolute;		/* 相对定位或绝对定位均可 */
    width:500px;
    height:300px;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: pink;	 	/* 方便看效果 */
}

⑤、利用flex布局,因为flex属性是css3的特性,需要考虑浏览器的兼容性

.container {
    display: flex;
    align-items: center; 		/* 垂直居中 */
    justify-content: center;	/* 水平居中 */
}
.container div {
    width: 100px;
    height: 100px;
    background-color: pink;		/* 方便看效果 */
}  

猜你喜欢

转载自blog.csdn.net/magic_xiang/article/details/82756791