css實現左(右)側固定寬度,右(左)側寬度自適應 ---清除浮動


老話長談,css的不固定適應布局   不管是面試還是在平時的工作中,這樣的布局形式一直都在用着,很常見,所以今天我就拿出來在嘮叨一下, 既是給自己一個備忘存儲,也是一個學習鞏固的參考,知道大家都會,還是要記憶一下,不為其他,就為打好基礎。

話說太多, 直接上代碼,一看就能明白。 也許你會不屑一顧的說簡單,可是我就喜歡寫一些。。。。。。作為一個菜鳥,就要從基礎努力學習才行。

方法多種, 你有新的方法可以補充說明,在此感謝!!

一、左邊布局固定,右邊自適應的布局

  *{ margin:0; padding:0}

   .whole{ width:100%;}

  <div class="whole">
        <p>自適應測試</p>
           <div class="left">固定左側 300px</div>
        <div class="right">右側自適應</div>
 </div>

 方法1: 左側用float浮動,給固定寬度,右側 左邊距的距離==左側層的寬度

    css代碼:
    
.left{ float:left;width:300px; background:red}
    .right{ margin-left:300px; background:green; }

 方法2:左邊絕對定位absolate,右邊代碼沒變化 還是右側 左邊距的距離==左側層的寬度;

  css代碼:

    .left{ position: absolute; left:0; width:300px; background:red}
    .right{ margin-left:300px; background:green; }

  方法3(個人喜好用):左右兩邊都用絕對定位absolute, 父級相對定義(不影響,建議加個相對定義,避免重疊) 

  css代碼:

    .left{ position: absolute; left:0; width:300px; background:red}

    .right{ position: absolute; left:300px; background:green; }

二、左邊布局不固定,右邊布局固定-----方法一致,位置換下而已

   <div class="whole">
        <p>自適應測試</p>
           <div class="left">左側自適應</div>
        <div class="right">右側寬度固定</div>
  </div>

  方法1、左側用左浮動,右邊距==右側層的寬度的負值(因為你是左撐開,距離右側的距離不錯層) 右側的有浮動,固定寬度

      .left{ float:left; width:100%; margin-right:-300px; background: red; }
  .right{ float: right; width: 300px;background: blue;}

 方法2、左右兩邊都用絕對定位absolute, 父級相對定義(不影響,建議加個相對定義,避免重疊)      

      .left{ position: absolute; left:0;  width: 100%;  background: red;}
  .right{ position: absolute;  left:200px; width:200px; background: green;}

 方法3、

 

 清除浮動的方法就一筆帶過, 都會

    1、在浮動層的下面單獨定義一個層 <div class="clear"></div>   .clear{ clear:both}

    2、偽類方法:after (用在父類的布局層上)-常用

         .father::after,.father::before{ clear: both; content: ""; display: table;}
     <div class='father'>
          <div class="son-flotleft"></div>
     <div class="son-flotrgt"></div>
     </div>

  3、父級元素設置overflow為hidden或者auto,固定高度 也可以--不建議 

         .father{overflow:hidden; width: 100%; }   //overflow:auto; height:300px;

寫的都比較簡單, 文字表述很少,都是代碼,說的思路再多,不讓直接代碼實際,用了后就明白意思了,good lucky。。

 

補充-- 禁止橫屏

<div class="orientation-alert"><p>
在豎屏下瀏覽效果更佳!
</p></div>


.orientation-alert{
background: rgba(0,0,0,.85);
position: fixed;
left: 0;
top: 0;
height: 100%;
width: 100%;
z-index: 1000000;
color: #FFF;
display: none;
}
.orientation-alert p{
position: absolute;
width: 100%;
top: 50%;
font-size: 20px;
line-height: 30px;
margin-top: -15px;
text-align: center;
}
@media screen and (orientation : landscape){
.orientation-alert{
     display: block;
   }
}
@media screen and (orientation : portrait){
.orientation-alert{
     display: none;
   }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM