[英]How can I make a dynamic width for elements based on the screen size?
這是我的代碼:
.container{ border:1px solid; width: 70%; } .el { border: 1px solid red; display: inline-block; min-width: 250px; }
<div class="container"> <div class="el">one</div> <div class="el">two</div> <div class="el">three</div> <div class="el">four</div> <div class="el">five</div> <div class="el">six</div> <div class="el">seven</div> <div class="el">eight</div> </div>
請運行上面的代碼中的代碼,點擊全頁按鈕,調整頁面大小。 我想將div.container
相等的部分。
因此,如果連續有三個元素( div.el
),則它們的width
應為33%
。 如果連續兩個元素,則width
應為50%
。
我怎樣才能做到這一點? 注意,我不想使用任何類似Bootstrap的框架。
看看媒體查詢
使用示例:
// Foo's original width is 100%
.foo {
width: 100%
}
@media screen and (max-width: 100px){
// Foo's width will be 50% when the view's width is below 100px
.foo {
width: 50%
}
}
... OR ...
@media screen and (min-width: 100px){
// Foo's width will be 50% when the view's width is over 100px
.foo {
width: 50%
}
}
嘗試使用CSS flex-box。 應用display:flex;
容器的屬性,並使用flex-grow: 1;
操作該容器中的.el
項目flex-grow: 1;
將其拉伸到屏幕的剩余寬度並相應地共享空間。
.container{ display: flex; width: 70%; border: 1px solid black; } .el { border: 1px solid red; flex-grow: 1; }
<div class="container"> <div class="el">one</div> <div class="el">two</div> <div class="el">three</div> <div class="el">four</div> <div class="el">five</div> <div class="el">six</div> <div class="el">seven</div> <div class="el">eight</div> </div>
CodePen示例: https ://codepen.io/CapySloth/pen/LLBgEB
.container{ border:1px solid; width: 70%; display: table; table-layout: fixed; } .el { border: 1px solid red; min-width: auto; display: table-cell; }
<div class="container"> <div class="el">one</div> <div class="el">two</div> <div class="el">three</div> <div class="el">four</div> <div class="el">five</div> <div class="el">six</div> <div class="el">seven</div> <div class="el">eight</div> </div>
鑒於我自己做的,幾乎可以肯定,最好的方法是使用flexbox的flex-wrap
來使項目溢出,而flex-grow
可以使它們占用盡可能多的空間。
<div id="cont">
<div>asdf</div>
<div>asdf</div>
<div>asdf</div>
<div>asdf</div>
<div>asdf</div>
<div>asdf</div>
<div>asdf</div>
<div>asdf</div>
<div>asdf</div>
<div>asdf</div>
</div>
#cont {
display: flex;
flex-wrap: wrap;
}
#cont div {
flex-grow: 1;
background: red;
padding: 10px;
margin: 10px;
}
請注意,這不是網格系統,因此最后一行不會遵循與所有先前(完整的)相同的列寬。 如果您希望單元格在空間可用的情況下溢出,並且在給定最后一行的情況下看起來像是網格,則需要添加一些JavaScript。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.