水平居中
- 内联元素
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 相等 - 块级元素
和水平居中处理原理相同
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。