时间:2021-07-01 10:21:17 帮助过:35人阅读
一、父元素的flex布局实现元素的水平垂直居中
示例代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.parent{
display:flex;
display:-webkit-flex;
justify-content: center;
align-items: center;
width:100%;
height: 200px;
background-color: #c43;
}
.child{
width:300px;
height:100px;
background-color: #c4235b;
}
</style>
</head>
<body>
<p class="parent">
<p class="child"></p>
</p>
</body>
</html>效果图如下:

二、绝对定位&负margin值实现元素水平垂直居中
注意:元素本身需要确定宽度和高度
示例代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
p{
width:300px;
height:100px;
background-color: #873cac;
position:absolute;
top:50%;
left:50%;
margin-left: -150px;
margin-top:-50px;
}
</style>
</head>
<body>
<p></p>
</body>
</html>效果图如下:

以上就是css实现元素水平垂直居中常见的两种方式实例详解的详细内容,更多请关注Gxl网其它相关文章!