水平居中
本文列举最常用的几种方式:
- margin:0 auto //为需要居中的元素加
- position:relative;相对定位 ,left的值需要计算
- position: absolute; 绝对定位
top: 0;
bottom: 0;
right: 0;
left: 0;
margin: auto; - 弹性盒子 display: flex;
//内联元素用: - 父元素加 :text-align: center;
- display: block; 变为块元素,再加宽度设置margin:0 auto;
- 弹性盒子也可以用
案例:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>居中案例</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
.box{
width: 200px;
height: 200px;
border: 1px solid #a124aa;
margin: 0 auto;
}
.box>.main{
width: 50px;
height: 50px;
background-color: aquamarine;
}
/* 上方是公共样式 */
/* 让main在大盒子里居中 */
/* 水平居中 一 */
.box1{
position: relative;
text-align: center;/* 内联元素居中 */
}
.box1>.main{
margin:0 auto; /* 块元素居中 */
}
/* 方式二 */
.box2>.main{
position: relative;
left: 75px;
}
.box2>span{
display: block;
width: 50px;
margin: 0 auto;
}
/* 方式三 */
.box3{
display: flex;
flex-direction: column;
align-items: center;
}
/* 方式四 */
.box4{
position: relative;
}
.box4>.main{
position: absolute;
top: 0; /* 用于垂直居中 */
bottom: 0; /* 用于垂直居中 */
right: 0;
left: 0;
margin: auto;
}
</style>
</head>
<body>
<div class="box box1">
<!-- 水平居中 内联元素span 和 块元素 p -->
<p class="main"></p>
<span>1234</span>
</div>
<div class="box box2">
<!-- 水平居中 方式二 -->
<p class="main"></p>
<span>1234</span>
</div>
<div class="box box3">
<!-- 水平居中 方式三 -->
<p class="main"></p>
<span>1234</span>
</div>
<div class="box box4">
<!-- 水平居中 方式四 -->
<p class="main"></p>
</div>
</body>
</html>
。。。垂直居中写在下篇博客了