簡體   English   中英

如何使一個容器填充另一個容器剩下的空間?

[英]How do you make a container fill the space left by another?

我已經嘗試了幾個小時,但似乎無法正確解決(抱歉,我的CSS不太好)。

我的目標是要有一個將在窗口寬度的整個寬度上顯示的容器。

  • 父容器的高度為200px。

此容器有2個子級,應在同一行中彼此相鄰放置。

  • 正確的容器具有固定的寬度(與高度相同,因此為200px)。
  • 左側容器的寬度應為=(當前窗口大小-200px)

我試過像這樣使用calc:

width: -webkit-calc(100% - 200px);

但這總是使我的寬度為-100%


兩個容器都顯示圖像輪播,但是為了簡單起見,我試圖使其與單個圖像一起使用。

*將正確的圖像適配到正確的容器應該是微不足道的,而且我已經設法使左邊的圖像擴展到寬度100%或高度100%,具體取決於哪個較小。 另外,我使用Java腳本將圖像居中。

我以為使用CSS可以輕松完成此操作,但也許我還需要使用Java腳本來在每次更改大小時重新計算寬度?

這是一張說明我要完成的圖像。 https://sketch.io/render/sk-733fbc35d88d981f5b7037c514ab2307.jpeg

在此處輸入圖片說明

您可以使用table屬性來解決此問題。

此解決方案是跨瀏覽器,但沒有flexboxcss calc

HTML:

<div class="container">
    <div class="left-div">left</div>
    <div class="right-div">right</div>
</div>

CSS:

.container{
    width: 100%;
    height: 200px;
    display: table;
}

.container > div{
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}
.container .right-div{
    width: 200px;
    background: #ddd;
}
.container .left-div{
    background: #ccc;
}

工作示例: https : //jsfiddle.net/en2qt3L5/3/

Flexbox FTW!

  • 將父容器上的display設置為flex
  • 將左側容器的width設置為100%
  • 將右側容器的width設置為200px

現場演示

 .container { width: 100%; height: 200px; display: flex; border: 2px solid blue; } .left { width: 100%; background-color: #185218; } .right { width: 200px; background-color: #8c1919; } .left, .right { height: 100%; color: white; font-family: sans-serif; font-size: 32px; text-align: center; } 
 <div class="container"> <div class="left">Variable width</div> <div class="right">Fixed width</div> </div> 

您總是可以在固定寬度的容器上使用float: right 只要確保你放置固定寬度的容器,然后設置margin-right的寬度可變的容器,以200px

此處的JSFiddle: https ://jsfiddle.net/7j8uh0td/

HTML:

<div class="parent">
  <div class="fixed-width">
    ...
  </div>
  <div class="vari-width">
    ...
  </div>
</div>

CSS:

.parent {
  width: 100%;
  height: 200px;
  border: 1px solid blue;
  color: white
}

.vari-width {
  width: auto;
  margin-right: 200px;
  background: green;
  height: 100%;
}

.fixed-width {
  float: right;
  width: 200px;
  height: 100%;
  background: red;
}

或者,您可以使用Flexbox-就像@Gothdo建議的:)

http://learnlayout.com/是一個很棒的網站,可以用作CSS的參考和示例(我至今仍在使用)

希望這可以幫助!

只需將子元素的display規則設置為inline-block ,然后應使用calc方法進行calc

這是一個例子。

 body { margin: 0; } .container { height: 200px; width: 100%; box-sizing: border-box; font-size: 0; } .left, .right { display: inline-block; } .left { width: calc(100% - 200px); min-height: 200px; background-color: green; } .right { background-color: tomato; height: inherit; width: 200px; } 
 <div class="container"> <div class="left"></div> <div class="right"></div> </div> 

暫無
暫無

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

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