css 未知宽高的元素实现水平方垂直居中

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>


<style type="text/css">
.parent{
display: table;
height:300px;
    width: 300px;
    background-color: #FD0C70;
}
.child{
display: table-cell;
vertical-align: middle;
font-size: 16px;
color: #fff;
text-align: center;
}
</style>
<body>
<!-- 方法一:父元素dispaly:table,子元素display:cell-table。 -->
<!-- 优势:父元素可以动态改变高度。
劣势:table属性容易造成多次reflow,IE8以下不支持 -->
<div class="parent">
    <div class="child">DEMO</div>
    </div>








    <style type="text/css">


    .par1{
    position: absolute;
    width: 500px;
    height: 500px;
    background: red;
    text-align: center;
    }
    .child1{
   
    background: pink;
    color: #fff;
    display: inline-block;


    }
    .par1:after{
    display: inline-block;
    content: "";
    width: 0;
    height: 100%;
    vertical-align: middle;
    }


    </style>
    <!-- 方法二:利用空元素或伪类  优点:兼容性好-->
     <div class="par1">
      <div class="child1">
      <p>你若暗火,便是晴天哈哈哈哈哈</p>
      <p>啦啦啦啦</p>
      </div>
     </div>




     <style type="text/css">
      .p3{
      position: relative;
      height:300px;
    width: 300px;
    background: #FD0C70;
      }
      .c3{
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%,-50%);
      color: #fff;


      }
     </style>


     <!--方法三:绝对定位+transform  优点:方便,支持webkit内核
缺点:transform兼容性差,IE9以下不支持 -->
     <div class="p3">
      <div class="c3">
      <p>你若暗火,便是晴天哈哈哈哈哈</p>
      <p>若果没有面试,就海投吧</p>
      </div>
     </div>

<style type="text/css">
.p4{
display: flex;
justify-content: center;
align-items: center;
width: 300px;
    height:300px;
    background: #FD0C70;
}
.c4{
color: #fff;
}
</style>
<!-- 方法4:flexbox布局  优点:方便
缺点:兼容性不好,IE支持很差 -->
<div class="p4">
      <div class="c4">
      <p>你若暗火,便是晴天哈哈哈哈哈</p>
      <p>若果没有面试,就海投吧</p>
      </div>
     </div>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值