元素垂直居中
方法一:容器设置height和line-height值相等
- 1 //css
- 2 .container{
- 3 width: 100px;
- 4 height: 100px;
- 5 line-height: 100px;
- 6 background-color: #ccc;
- 7 }
- 8
- 9 //html
- 10 <div class="container">
- 11 单行文本
- 12 </div>
– 优点: 适用于所有浏览器
– 缺点: 仅适用于单行文本
方法二: 内容设置绝对定位(position:absolute),并将top设置为50%,margin-top设置为height的一半
- 1 //css
- 2 .container{
- 3 width: 200px;
- 4 height: 200px;
- 5 border: 1px solid red;
- 6 position: relative;
- 7 }
- 8 .content{
- 9 background-color: #ccc;
- 10 height: 50px;
- 11 width: 100%;
- 12 position: absolute;
- 13 top: 50%;
- 14 margin-top: -25px;
- 15 }
- 16
- 17 //html
- 18 <div class="container">
- 19 <div class="content"></div>
- 20 </div>
– 优点: 适用于所有浏览器
– 缺点: 内容高度必须固定
方法三:设置vertical-align:middle;属性+:after伪元素
- 1 //css
- 2 .wrapper {
- 3 width: 500px;
- 4 height: 500px;
- 5 background-color: #ccc;
- 6 text-align: center;
- 7 }
- 8
- 9 .wrapper:after {
- 10 content: '';
- 11 height: 100%;
- 12 width: 0;
- 13 display: inline-block;
- 14 vertical-align: middle;
- 15 }
- 16
- 17 .align {
- 18 background-color: #f00;
- 19 width: 20%;
- 20 height: 20%;
- 21 display: inline-block;
- 22 vertical-align: middle;
- 23 }
- 24
- 25 //html
- 26 <div class="wrapper">
- 27 <div class="align"></div>
- 28 </div>
– 优点: 内容高度不必固定
– 缺点: 代码繁琐
方法四:利用flex布局(display:flex;),设置justify-content:center;垂直对齐,设置align-items:cneter;水平对齐
- 1 //css
- 2 .wrapper {
- 3 width: 500px;
- 4 height: 500px;
- 5 background-color: #ccc;
- 6 display: flex;
- 7 justify-content: center;
- 8 align-items: center;
- 9 }
- 10
- 11 //html
- 12 <div class="wrapper">
- 13 <div class="align">我是内容</div>
- 14 </div>
– 优点: 代码简单
– 缺点: flex布局浏览器兼容性不好
方法五: 设置内容绝对定位(position:absolute)+移动元素位置(transform:translate(-50%,-50%);)
- 1 //css
- 2 .wrapper {
- 3 width: 500px;
- 4 height: 500px;
- 5 background-color: #ccc;
- 6 position: relative;
- 7 }
- 8
- 9 .align {
- 10 position: absolute;
- 11 top: 50%;
- 12 left: 50%;
- 13 transform: translate(-50%, -50%);
- 14 }
- 15
- 16 //html
- 17 <div class="wrapper">
- 18 <div class="align">我是内容</div>
- 19 </div>
– 优点: 内容高度不必固定
– 缺点: transform属性兼容性不好
方法六:设置内容绝对定位(position:absolute)+(margin:auto;)
- 1 //css
- 2 .wrapper {
- 3 position: relative;
- 4 width: 500px;
- 5 height: 500px;
- 6 border: 1px solid red;
- 7 }
- 8 .content{
- 9 position: absolute;
- 10 width: 200px;
- 11 height: 200px;
- 12 border: 1px solid green;
- 13 top: 0;
- 14 bottom: 0;
- 15 left: 0;
- 16 right: 0;
- 17 margin:auto;
- 18 }
- 19
- 20 //html
- 21 <div class="wrapper">
- 22 <div class="content"></div>
- 23 </div>