css 寬高自適應的div元素以及如何垂直置中

來源:互聯網
上載者:User
在我們 編寫css 樣式的時候經常會遇見一個問題 那就是一個 寬高未知的元素 要讓他 垂直置中如何?這個呢 下面是我常用的兩種方法

上代碼

  下面的是 結構代碼

<div class="wrap">//此處為父組件 我們會設定父級的寬高並讓其置中  <div class="center">//子組件我們要實現它的垂直置中 不設定他的寬高 寬高 都由下面的img引入的圖片撐開  <img width="100px" src="img/logo.a68568a.png"/>  </div>  </div>

  下面是樣式代碼

.wrap{設定一個置中的外框        width: 500px;height: 400px;border: 1px solid black;margin: 0 auto;text-align: center;//水平置中}.wrap:before{//設定一個寬度為0的偽類為什麼要設定這個偽類 起時這個偽類起到了一個對準線的作用display: inline-block;content: '';height: 100%;width: 0;vertical-align: middle;//垂直置中}.center{//這個時候 在對我們的centerdiv 設定 vertical-align: middle 就可垂直置中了vertical-align: middle;display: inline-block;}img{vertical-align: top;}

  二 css3 transform解決

.wrap{//一個固定寬高 置中的外框width: 500px;height: 400px;border: 1px solid black;margin: 0 auto;}    .center{//我們的center div 還是寫成inline-block 的樣式         position: relative;          //相對定位 通過相對定位left  top 值的設定來讓center div 的左上方的位置 為wrap 的中心          //但這個時候我們還不是完全垂直置中 因為我們的center div 本身也有自適應的寬高 這個時候 就要用到transform了          //通過translateX(-50%) translateY(-50%) 讓center 本身在x軸y軸上位移50% 達到真正的置中(軸心點預設在左上方)          //注意transform各個瀏覽器有不同的首碼並且不相容ie8 以下 top: 50%; left: 50%; display: inline-block;-webkit-transform: translateX(-50%) translateY(-50%);}img{vertical-align: top;}
<!DOCTYPE html><html><head><meta charset="utf-8" /><title></title><style type="text/css">document{height: 100%;}html{height: 100%;}body{height: 100%;overflow: hidden;margin: 0;}#bigwrap{width: 100%;height: 100%;text-align: center;}#bigwrap:before{height: 100%;width: 0;vertical-align: middle;content: '';display: inline-block;}.wrap{width: 500px;height: 400px;border: 1px solid black;margin: 0 auto;text-align: center;}.wrap:before{display: inline-block;content: '';height: 100%;width: 0;vertical-align: middle;}.center{vertical-align: middle;display: inline-block;}img{vertical-align: top;}/*.center {   position: fixed;  top: 50%;  left: 50%;  background-color: #000;  width:50%;  height: 50%;-webkit-transform: translateX(-50%) translateY(-50%);}*/</style></head><body><!--<div id="bigwrap">--><div class="wrap"><div class="center"><img width="100px" src="img/logo.a68568a.png"/></div></div></div></body></html>
相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.