有時候,我們可能會產生多個div標簽橫向排列而不換行的需求,具體有以下幾種實現方法:
1. 同級div設置display:inline-block,父級div強制不換行
例如:
<html> <head></head> <body> <div id="container"> <div class="lable">測試測試</div> <div class="lable">測試測試</div> <div class="lable">測試測試</div> <div class="lable">測試測試</div> <div class="lable">測試測試</div> <div> </body> <style> #container { width:400px; height: 200px; background-color: red; overflow: auto; white-space: nowrap; } .lable { width: 100px; background-color: blue; display: inline-block; } </style> </html>
2. 通過position絕對定位實現
例如:
<html> <head></head> <body> <div id="container"> <div id="lable1">測試測試</div> <div id="lable2">測試測試</div> <div id="lable3">測試測試</div> <div id="lable4">測試測試</div> <div id="lable5">測試測試</div> <div> </body> <style> #container { width:400px; height: 200px; background-color: red; overflow: auto; position: relative; } #lable1 { width: 100px; margin-left: 0; background-color: blue; position: absolute; } #lable2 { width: 100px; margin-left: 100px; background-color: blue; position: absolute; } #lable3 { width: 100px; margin-left: 200px; background-color: blue; position: absolute; } #lable4 { width: 100px; margin-left: 300px; background-color: blue; position: absolute; } #lable5 { width: 100px; margin-left: 400px; background-color: blue; position: absolute; } </style> </html>
3. 通過flex方式實現
具體請參考:Flex 布局教程:語法篇
例如:
<html> <head></head> <body> <div id="container"> <div class="lable">測試測試</div> <div class="lable">測試測試</div> <div class="lable">測試測試</div> <div class="lable">測試測試</div> <div class="lable">測試測試</div> <div> </body> <style> #container { width:400px; height: 200px; background-color: red; display: flex; display: -webkit-flex; /* 從左端開始沿水平軸防止flex item */ flex-direction: row; /* 強制 flex item不換行,沿着同一行堆疊 */ flex-wrap: nowrap; /* flex item在主軸上的對齊方式,這里定義左對齊 */ justify-content: flex-start; /* 定義交叉軸對其方式 */ align-items: flex-start } .lable { width: 100px; margin-left: 5px; background-color: blue; } </style> </html>
不過,這樣以來,flex容器的overflow屬性將不再起作用。在flex布局下,所有的flex item均分或根據開發者定義分配容器空間,而不會超過flex容器空間。
注意
值得注意的時,如果僅僅設置父div容器的overflow屬性,容器內的元素均為inline或者inline-block,也無法一直堆疊在同一行而不換行,他們無法撐開父容器。當一行無法放置下它們時間,他們會自動換行。
————————————————
版權聲明:本文為CSDN博主「Kiloveyousmile」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/Kiloveyousmile/article/details/80248083