步骤:
1、给父级元素添加相对定位position:relative;
2、子元素设置如下:
position: absolute;
left: 50%;
top: 50%;
//设置为子元素width的一半,设置为负值
margin-left: -25px;
//设置为子元素height的一半,设置为负值
margin-top: -25px;
代码案例如下:
<!DOCTYPE html>
<html>
<head>
<title>块级元素在块级元素内部垂直居中</title>
</head>
<style type="text/css">
.external{
width: 100px;
height: 100px;
background-color: red;
position: relative;
}
.internal{
width: 50px;
height: 50px;
background-color: blue;
position: absolute;
left: 50%;
top: 50%;
margin-left: -25px;
margin-top: -25px;
}
</style>
<body>
<div class="external">
<div class="internal"></div>
</div>
</body>
</html>
本文介绍了一种利用CSS属性使块级元素在其父元素内水平和垂直居中的方法。通过给父级元素添加相对定位,并对子元素使用绝对定位,结合left、top属性和负值的margin属性,实现子元素的精确居中。案例代码展示了具体的实现细节。
2505

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



