前端笔记之Div居中显示
1、水平居中:给div设置一个宽度,然后添加margin:0 auto属性
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>W3Cschool</title>
<style type="text/css">
div{
width: 300px;
height: 300px;
background-color: #000;
}
#div1{
width: 200px;
margin: 0 auto;
background-color: #f40;
}
</style>
</head>
<body>
<div>
<div id="div1"></div>
</div>
</body>
</html>
2、水平垂直居中一
确定容器的宽高 宽200 高 100 的层
设置层的外边距
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>W3Cschool</title>
<style type="text/css">
div{
position: relative;
width: 300px;
height: 300px;
background-color: #000;
}
#div1{
position: absolute; /* 相对定位或绝对定位均可 */
width:200px;
height:100px;
top: 50%;
left: 50%;
margin: -50px 0 0 -100px; /* 外边距为自身宽高的一半 */
background-color: #f40; /* 方便看效果 */
}
</style>
</head>
<body>
<div>
<div id="div1"></div>
</div>
</body>
</html>
3、水平垂直居中二
未知容器的宽高,利用 transform 属性
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>W3Cschool</title>
<style type="text/css">
div{
position: relative;
width: 300px;
height: 300px;
background-color: #000;
}
#div1{
position: absolute; /* 相对定位或绝对定位均可 */
width:200px;
height:100px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: #f40; /* 方便看效果 */
}
</style>
</head>
<body>
<div>
<div id="div1"></div>
</div>
</body>
</html>
4、水平垂直居中三
利用 flex 布局
实际使用时应考虑兼容性
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>W3Cschool</title>
<style type="text/css">
div{
width: 300px;
height: 300px;
display: flex;
align-items: center; /* 垂直居中 */
justify-content: center; /* 水平居中 */
background-color: #000;
}
#div1{
width:200px;
height:100px;
background-color: #f40; /* 方便看效果 */
}
</style>
</head>
<body>
<div>
<div id="div1"></div>
</div>
</body>
</html>