1. 程式人生 > >多個div排列在同一行而不換行

多個div排列在同一行而不換行

  有時候,我們可能會產生多個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方式實現

<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,也無法一直堆疊在同一行而不換行,他們無法撐開父容器。當一行無法放置下它們時間,他們會自動換行。