簡體   English   中英

CSS並排div與Pixel和百分比寬度

[英]CSS side by side div with Pixel and Percent widths

我在父div中有兩個div(並排),我希望右div占據剩余空間的100%(即100% - 200px)並且應該始終保持在左邊div(不在左邊div之下):

 <div id="wrapper" style="width: 100%;"> <div id="left" style="background-color: Blue; height: 100px; float: left; width: 200px;"></div> <div id="right" style="background-color: Aqua; height: 100px; float: left; width: 100%;"></div> <div style="clear: both;"></div> </div> 

由於您只有一個固定寬度的列,因此將其向左浮動即可。 至於第二列,不要指定浮點數和寬度; 這確保它是100%寬。 但是你必須添加左邊距; 否則第二列將干擾浮動柱,例如

  • 淺綠色背景將出現在藍色背景后面(關閉藍色背景,看看我的意思)
  • 如果第二列變得比第一列高,則其他內容將開始出現在第一列下方。

 <div id="wrapper"> <div id="left" style="background-color: Blue; height: 100px; float: left; width: 200px;"></div> <div id="right" style="background-color: Aqua; height: 100px; margin-left: 200px;"></div> <div style="clear: both;"></div> </div> 

使父包裝器float 你也可能想要刪除第二個子div中的width: 100% 並且其寬度由內部的內容量設置。 或者你可以擁有兩個子div的百分比。 30%70%

在這里演示

向右側div添加位置屬性。 左div 200px和右div占用剩余空間。

#right{
    background-color:Aqua;
    height:100px;
    position:absolute;
    top:0;
    right:0;
    left:200px;
}

查看http://jsfiddle.net/EpA5F/1/上的工作示例

好的,所以在較新的瀏覽器上我們可以使用display:box; 和box-flex:1,...屬性。 我目前在一個只需要Chrome的webproject中使用它,所以這個新的CSS3東西為我解決了很多問題。

接受的答案是好的,但我有一個問題,正確的欄目不足以支持我的子導航,因為它也是浮動的。

使用現代瀏覽器,您現在可以將所有元素浮動,並使用更酷的CSS獲得相同的效果。 使用“width:calc(100% - 380px);” 意味着你可以漂浮你的元素,讓它們正確定位,看起來很酷......

.container { float: left; width: 100%; }
.container__left { float: left; width: 380px; height: 100px; background: blue; }
.container__right { float: right; width: calc(100% - 380px); height: 100px; background: green; }

演示http://jsfiddle.net/auUB3/1/

如果你想要正確的div具有恆定的寬度:

 <div style="position:relative">
   <div class='wrapper'>
      <div style="width: 70%"></div>
      <div style="width: 20%"></div>
      <div style="width: 10%"></div>
      <div style="clear:both"></div>
   </div>
   <div class="constant-width"><div>
 </div>

和CSS

 .wrapper{
     margin-right: CONSTANTpx;
 }
 .wrapper div{
     float:left;
 }
 .constant-width{
     top: 0px; right:0px; position:absolute;
     width: CONSTANTpx
 }

工作良好無國界

的jsfiddle

你的左邊div應該左邊浮動,它的像素寬度使用位置相對。 你的右邊div應該只有相對位置,也許隱藏溢出。 這應該可以解決您的問題。 不需要使用清除浮動的div。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM