经典的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>