程度居中
- 内联元素
text-align:center
- 块级元素程度居中
定宽状况下:
1、利用margin
margin-left:auto;
margin-right:auto;
2、margin负值+相对定位
<!DOCTYPE html>
<html>
<head>
<style>
.parent{
position: relative;
width: 100%;
}
.child{
width: 200px;
height: 200px;
position: absolute;
left: 50%;
margin-left: -100px;
background-color: cyan;
}
</style>
</head>
<body>
<div class="parenet">
<p class="child">margin负值+相对定位设置程度居中</p>
</div>
</body>
</html>
3、相对定位+margin auto
<!DOCTYPE html>
<html>
<head>
<style>
.parent{
position: relative;
width: 100%;
}
.child{
width: 200px;
height: 200px;
position: absolute;
left: 0;
right: 0;
margin: auto;
background-color: cyan;
}
</style>
</head>
<body>
<div class="parenet">
<p class="child">相对定位+margin auto设置程度居中</p>
</div>
</body>
</html>
4、flex布局
<!DOCTYPE html>
<html>
<head>
<style>
.parent{
display: flex;
justify-content: center;
width: 100%;
}
.child{
width: 200px;
background-color: cyan;
}
</style>
</head>
<body>
<div class="parent">
<p class="child">flex程度居中</p>
</div>
</body>
</html>
宽度未知状况下:
1、相对定位,左右间隔设置雷同
<!DOCTYPE html>
<html>
<head>
<style>
.parent{
position: relative;
}
.child{
position: absolute;
left:25%;
right: 25%;
background-color: cyan;
}
</style>
</head>
<body>
<div class="parenet">
<p class="child">相对定位设置程度居中,宽度未知</p>
</div>
</body>
</html>
2、相对布局+translate
<!DOCTYPE html>
<html>
<head>
<style>
.parent{
position: relative;
}
.child{
position: absolute;
left: 50%;
transform: translate(-50%);
background-color: cyan;
}
</style>
</head>
<body>
<div class="parenet">
<p class="child">相对定位设置程度居中,宽度未知</p>
</div>
</body>
</html>
垂直居中
- 行内元素状况
height 和 line-height 相等 - 块级元素
和程度居中解决原理雷同
发表回复