3. 下列 html 结构中, 如何让子元素在父元素中垂直, 水平居中.
- <div class="parent">
- <div class="child">
- </div>
- </div>
一共有七种方法:
(1) 定位 + margin:auto
注意: 兼容性较好, 缺点: 不支持 IE7 以下的浏览器
- .parentr {
- position: relative;
- width: 300px;
- height: 300px;
- background: yellow;
- }
- .child {
- position: absolute;
- left: 0;
- top: 0;
- right: 0;
- bottom: 0;
- margin: auto;
- width: 100px;
- height: 100px;
- background: red;
- }
(2) 定位 + margin-left+margin-top
注意: 兼容性好; 缺点: 必须知道元素的宽高
- .parent {
- position: relative;
- width: 300px;
- height: 300px;
- background: yellow;
- }
- .child {
- position: absolute;
- left: 50%;
- top: 50%;
- margin-left: -50px;
- margin-top: -50px;
- width: 100px;
- height: 100px;
- background: red;
- }
来源: http://www.bubuko.com/infodetail-3129494.html