赞
踩
给容器添加样式
- display: flex;
- justify-content: center;
- align-items: center;
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <title>Document</title>
- <style>
- .box {
- display: flex;
- justify-content: center;
- align-items: center;
- border: 1px solid gray;
- width: 200px;
- height: 100px;
-
- }
-
- .item {
- width: 50px;
- height: 50px;
- background-color: yellow;
- }
- </style>
- </head>
- <body>
- <div class="box">
- <span class="item">水平垂直居中</span>
- </div>
- </body>
- </html>

限制条件:浏览器需支持CSS3,比较老的浏览器不适用
给容器(父元素)添加样式
position: relative
给内部元素添加样式
- position: absolute;
- top: 50%;
- left: 50%;
- transform: translate(-50%, -50%);
给容器(父元素)添加样式
position: relative
给内部元素添加样式
- position: absolute;
- top: 0;
- bottom: 0;
- left: 0;
- right: 0;
- margin: auto;
限制条件:需知道内部元素的宽度和高度
给容器(父元素)添加样式
position: relative
给内部元素添加样式
- position: absolute;
- left:50%;
- margin-left:-内部元素宽度的一半;
- top: 50%;
- margin-top: -内部元素高度的一半;
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <title>Document</title>
- <style>
- .box {
- margin: 30px 30px 0px 300px;
- border: 1px solid gray;
- height: 100px;
- position: relative;
- }
- .item {
- background-color: yellow;
- position: absolute;
- left: 50%;
- margin-left: -150px;
- top: 50%;
- margin-top: -25px;
- width: 300px;
- height: 50px;
- }
- </style>
- </head>
- <body>
- <div class="box">
- <span class="item">水平垂直居中 -- 子绝父相 + 负外边距</span>
- </div>
- </body>
- </html>

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。