css实现水平垂直居中,笔记
方法有4种
一、最常用的方法 利用绝对定位+transform
<!doctype html>
<html>
<head>
<title>css实现水平垂直居中</title>
<style>
.div{
width: 800px;
height: 600px;
background-color: #f5f5f5;
position: relative;
}
.box{
width: 200px;
height: 200px;
background-color: #ff0000;
position: absolute;
left: 50%;
top: 50%;
transform: translateX(-50%) translateY(-50%)
}
</style>
</head>
<body>
<div class="div">
<div class="box">
</div>
</div>
<body>
</html>
二、flex居中
<html>
<head>
<title>css实现水平垂直居中</title>
<style>
.div{
width: 800px;
height: 600px;
background-color: #f5f5f5;
display: flex;
justify-content: center;
align-items: center;
}
.box{
width: 200px;
height: 200px;
background-color: #ff0000;
}
</style>
</head>
<body>
<div class="div">
<div class="box">
</div>
</div>
<body>
</html>
三、父元素display: flex,子元素marin auto