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
本文介绍了使用CSS实现水平垂直居中的四种方法:绝对定位+transform、flex布局等。适合前端开发者学习并应用于网页布局。
3049

被折叠的 条评论
为什么被折叠?



