【盒子水平垂直居中的三种(四种)方式】
- 效果
- 方法一:利用margin:auto
- 方法一:利用定位(子绝父相)
- 方法三:利用flex布局
- 方法四:利用计算外边距(和margin:auto相似)
效果

方法一:利用margin:auto
margin: auto;和 margin-top: ;搭配使用
| <style> |
| * { |
| padding: 0; |
| margin: 0; |
| } |
| .parent { |
| position: fixed; |
| width: 900px; |
| height: 600px; |
| background-color: aqua; |
| } |
| .children { |
| margin: auto; |
| margin-top: 150px; |
| width: 300px; |
| height: 300px; |
| background-color: pink; |
| } |
| </style> |
| </head> |
| <body> |
| <div class="parent"> |
| <div class="children"> |
| |
| </div> |
| </div> |
| </body> |
复制
方法一:利用定位(子绝父相)
父盒子使用相对定位,子盒子使用绝对定位,利用top:50% left:50% 让子盒子相距父盒子上边界,左边界宽高的50% 利用 margin-top margin-left返回子盒子自身宽高的50%
| <style> |
| * { |
| padding: 0; |
| margin: 0; |
| } |
| .parent { |
| position: relative; |
| width: 900px; |
| height: 600px; |
| background-color: aqua; |
| } |
| .children { |
| position: absolute; |
| top: 50%; |
| |
| left: 50%; |
| |
| margin-top: -150px; |
| |
| margin-left: -150px; |
| |
| width: 300px; |
| height: 300px; |
| background-color: pink; |
| } |
| </style> |
| </head> |
| <body> |
| <div class="parent"> |
| <div class="children"> |
| |
| </div> |
| </div> |
| </body> |
复制
方法三:利用flex布局
| <style> |
| * { |
| padding: 0; |
| margin: 0; |
| } |
| .parent { |
| display: flex; |
| |
| justify-content: center; |
| |
| align-items: center; |
| width: 900px; |
| height: 600px; |
| background-color: aqua; |
| } |
| .children { |
| width: 300px; |
| height: 300px; |
| background-color: pink; |
| } |
| </style> |
| </head> |
| <body> |
| <div class="parent"> |
| <div class="children"></div> |
| </div> |
| </body> |
复制
方法四:利用计算外边距(和margin:auto相似)
| <style> |
| * { |
| padding: 0; |
| margin: 0; |
| } |
| .parent { |
| position: fixed; |
| width: 900px; |
| height: 600px; |
| background-color: aqua; |
| } |
| .children { |
| |
| margin-top: 150px; |
| |
| margin-left: 300px; |
| width: 300px; |
| height: 300px; |
| background-color: pink; |
| } |
| </style> |
| </head> |
| <body> |
| <div class="parent"> |
| <div class="children"></div> |
| </div> |
| </body> |
复制