[英]how do I make a container offset to the left at a particular point and fill the remaining space in css
例如, .container-a
有這些 styles:
.container-a {
max-width: 1240px;
margin: 0 auto;
}
這意味着.container-a
永遠不會超過 1240px 的定義寬度。 左右自動邊距意味着瀏覽器會自動計算左右兩側的相等邊距,無論屏幕有多大,它始終居中。
現在,假設我想要另一個容器。 這個container-b
應該偏移與.container-a
向左偏移相同的左邊距,這意味着.container-a
和.container-b
從同一點開始。 唯一的區別是這個特定container-b
沒有偏移右邊距並且沒有定義的最大寬度,這意味着它會填充瀏覽器 window 上剩余的可用空間,而不管屏幕有多大。 這可能嗎?我該如何實現?
而不是其他答案中建議的絕對定位,我會在這里使用calc()
go,它允許你在 CSS 中做一些基本的數學運算。(絕對定位不是基本布局的工具,並且可以導致很多其他文檔流的 rest 問題。)
訣竅是簡單地將可用的 window 寬度 (100%) 分成兩半,減去容器 a 的最大寬度的一半 - 然后將其設置為容器 b 的 margin-left。
我在這里使用了較小的 500px 最大寬度,以便在呈現的片段中可以很容易地看到效果,但是您可以輕松地相應地修改它,以獲得您實際需要的最大寬度。
div { background: #ccc; }.container-a { max-width: 500px; margin: 1em auto; }.container-b { margin: 1em auto; margin-left: calc(100% / 2 - 250px) /* 250px = half the max-width of container a */ }
<div class="container-a"> I am container-a </div> <div class="container-b"> I am container-b </div>
您可能希望將其包裝到一個媒體查詢中,這樣當可用的 window 寬度小於最大寬度時它就不會出現錯誤行為(因為這會導致此處容器 b 的左邊距為負數。)
你可以這樣做:
<div class='c'>
<div class='c1'>container</div>
<div class='c2'>container</div>
</div>
.c {
width: 400px;
margin: 0 auto;
}
.c1 {
background: red;
margin: 0 auto;
}
.c2 {
background: blue;
position: absolute;
width: 100%;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.