經典的css布局有以下幾種,下面分別用不同的方法進行實現且進行對比。
一、水平居中
水平居中布局指的是當前元素在父級元素的容器中,水平方向上顯示的是居中的,有以下幾種方式來完成布局:
1、margin:0 auto; text-align:center實現水平居中。
直接給子元素加上margin:0 auto; text-align:center來實現.實際中用的最多,但有一個小問題就是如果子元素里有文本內容,文本內容也會居中。
2、display:table或者是display:inline-block配合margin來實現
3、相對定位實現居中
4、絕對定位實現居中,使用絕對定位有一點就是父元素要加上相對定位
5、flex實現水平居中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>css實現水平居中</title>
<style> * { margin: 0; padding: 0;
} .box1 { width: 100%; height: 100px; background: beige;
/* position: relative; */
/* display: flex; flex-direction: column; */ display: flex;
} .box2 { width: 100px; height: 100px; background: greenyellow;
/* margin:0 auto; 第1種方式來水平居中 text-align: center; */
/* display: table; margin:0 auto; 第2種方式來水平居中 */
/* position: relative; left: 50%; transform: translateX(-50%); 第3種方式來水平居中 */
/* position: absolute; left:50%; transform: translateX(-50%); 第4種方式來水平居中 */
/* align-self: center; 第5種方式來水平居中 */
/* margin: auto; 第5種方式來水平居中,和display:flex配合使用 */
}
</style>
</head>
<body>
<div class="box1">
<div class="box2">box2</div>
</div>
</body>
</html>
二、垂直居中
垂直居中布局指的是當前元素在父級元素的容器中,垂直方向顯示是居中的,有以下幾種方式來完成布局:
1、table-cell和vertical-align屬性配合使用
給父元素添加display:table-cell;顯示的效果等同於表格中的單元格(單元格的內容允許水平或者是垂直方向的對齊設置)
vertical-align:center;垂直方向上的居中
2、絕對定位和transform屬性配合使用
這個要給父級一個相對定位
3、flex實現垂直居中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>垂直居中</title>
<style> * { padding:0; margin: 0;
} .box1{ width: 100px; height: 500px; background-color: rgb(223, 223, 241);
/* display: table-cell; vertical-align: middle; 第1種方法實現垂直居中 */
/* position: relative; */
/* display: flex; flex-direction: column; justify-content: center; 第3種方法實現垂直居中 */
} .box2{ width: 100px; height: 100px; background: greenyellow; position: absolute;
/* top:50%; transform: translateY(-50%); 第2種方法實現垂直居中 */
}
</style>
</head>
<body>
<div class="box1">
<div class="box2">box2</div>
</div>
</body>
</html>
三、居中布局
居中布局就是即水平居中又垂直居中
1、絕對定位加上transform實現居中布局
要給父級加上相對定位,還有一點問題就是兼容性的問題
要給父級元素加上:position:relative;
子元素加上:position:absolute;top:50%;left:50% ;transform: translate(-50%,-50%);
2、table+margin來實現水平居中,table-cell和vertical-align實現垂直居中
有一點問題就是有可能會影響整體的布局效果沒有絕對定位好
要給父級元素加上:display:table-cell;vertical-align:middle;
子元素加上:display:table;margin:0 auto;
3、flex來實現水平垂直居中,它的作用最大
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>水平垂直居中</title>
<style> *{ margin:0; padding:0;
} .box1{ width: 500px; height: 500px; background-color: greenyellow;
/* position: relative; 第1種水平垂直居中方式*/
/* display: table-cell; 第2種水平垂直居中方式 vertical-align: middle; */
/* display: flex; justify-content: center; 第3種水平垂直居中方式 */
} .box2{ width: 100px; height: 100px; background-color: pink;
/* position: absolute; 第1種水平垂直居中方式 top:50%; left: 50%; transform: translate(-50%,-50%); */
/* display: table; 第2種水平垂直居中方式 margin: 0 auto; */
/* align-self: center; 第3種水平垂直居中方式 */
}
</style>
</head>
<body>
<div class="box1">
<div class="box2">box2</div>
</div>
</body>
</html>