绝对定位水平垂直居中 [margin:auto 实现绝对定位元素的居中]
1. 代码
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <title></title>
- <style>
- .container{
- width: 400px;
- height:400px;
- position: absolute;
- border:1px solid #e8e8e8;
- }
- .inner{
- width: 200px;
- height:200px;
- background: green;
- position: absolute;
- left: 0;
- right: 0;
- top: 0;
- bottom: 0;
- margin:auto;
- }
- </style>
- </head>
- <body>
- <div class="container">
- <div class="inner">
- </div>
- </div>
- </body>
- </html>
2. 效果
图 1.png
绝对定位水平垂直居中 [margin 负间距]
1. 代码
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <style>
- .container{
- width: 400px;
- height:400px;
- border:1px solid #e8e8e8;
- position: absolute;
- }
- .inner{
- width: 200px;
- height: 200px;
- position: absolute;
- top:50%;
- left:50%;
- margin-top: -100px;
- margin-left: -100px;
- background: green;
- }
- </style>
- </head>
- <body>
- <div class="container">
- <div class="inner">
- </div>
- </div>
- </body>
- </html>
2. 效果
图 2.png
绝对定位水平垂直居中 [Transforms 变形]
1. 代码
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <style>
- .container{
- width: 400px;
- height:400px;
- border:1px solid #e8e8e8;
- position: absolute;
- }
- .inner{
- width: 200px;
- height:200px;
- position:absolute;
- top:50%;
- left:50%;
- transform: translate(-50%,-50%);
- background: green;
- }
- </style>
- </head>
- <body>
- <div class="container">
- <div class="inner">
- </div>
- </div>
- </body>
- </html>
2. 效果
图 3.png
使用绝对定位使 div 元素相对于父元素进行垂直居中定位时, 要将父元素的 position 设置为除了 static 以外的属性值, 这样才会有效果.
不定宽高水平垂直居中
1. 代码
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <style>
- .container{
- height: 400px;
- width: 400px;
- display: flex;
- justify-content: center;
- align-items: center;
- border:1px solid #e8e8e8;
- }
- .inner{
- width: 200px;
- height: 200px;
- background: green;
- }
- </style>
- </head>
- <body>
- <div class="container">
- <div class="inner">
- </div>
- </div>
- </body>
- </html>
2. 效果
图 4.png
不定宽高意味着 div 垂直居中时, 父元素可以在不设置宽度和高度的情况下, 根据子元素的宽, 高作出相应的改变.
来源: http://www.jianshu.com/p/60551816d522