多个div排列在同一行而不换行

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Kiloveyousmile/article/details/80248083

  有时候,我们可能会产生多个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,也无法一直堆叠在同一行而不换行,他们无法撑开父容器。当一行无法放置下它们时间,他们会自动换行。

参考

1. 怎样使float元素超过父元素的width强制不换行?
2. 如何让多个div横向排列而不换行

猜你喜欢

转载自blog.csdn.net/Kiloveyousmile/article/details/80248083