关于浮动元素垂直居中的问题

两种浮动元素垂直居中的情况: 父盒子有宽高; 父盒子没有宽高
下面时 HTML 中的代码:
 1 <!DOCTYPE html>
 2 <html>
 3 <head lang="en">
 4     <meta charset="UTF-8">
 5     <title>浮动元素垂直居中</title>
 6 </head>
 7 <body>
 8 <div class="parent">
 9     <div class="child"></div>
10 </div>
11 </body>
12 </html>
 
 

一. 父盒子有宽高:

垂直居中前代码实现 :

 1         .parent {
 2             width: 150px;
 3             height: 150px;
 4             background-color: teal;
 5             position: relative; /*注意父盒子要相对定位*/
 6         }
 7         .child {
 8             width: 50px;
 9             height: 50px;
10             background-color: violet;
11             float: left;
12        }    

垂直居中前效果图 :

垂直居中代码实现 :

 1           .parent {
 2               width: 150px;
 3               height: 150px;
 4               background-color: teal;
 5               position: relative; /*注意父盒子要相对定位*/
 6 }
 7           .child {
 8               width: 50px;
 9               height: 50px;
10              background-color: violet;
11              float: left;
12 13              position: absolute;
14              top: 50%;  /*容器的一半*/
15              left: 50%;
16              margin-top: -25px;  /*子盒子高度的一半*/
17              margin-left: -25px;  /*子盒子宽度的一半*/
18 }

垂直居中效果图 :

 


二. 父盒子没有宽高:
 1         .parent {
 2             background-color: limegreen;
 3             position: relative;
 4         }
 5         .child {
 6             width: 50px;
 7             height: 50px;
 8             background-color: khaki;
 9             float: left;
10             margin: auto;
11 
12             position: absolute;
13             top: 0;
14             left: 0;
15             right: 0;
16             bottom: 0;
17         }

由于父盒子是没有宽高的, 所以子盒子就相对于页面中间垂直居中了

 

转载于:https://www.cnblogs.com/whuiy/p/6087702.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值