我想将多个div放在同一行中,但是一个总是放在另一个之下。我该怎么办?

查看:https://jsfiddle.net/Alana2597/4pnakz8a/



.content {
  width: 240px;
  overflow-x: scroll;
  overflow-y: hidden;
  max-height: 100px;
  height: 100px;
}

#div1 {
  height: 300px;
  width: 100px;
  border: solid 1px #000000;
  background-color: #0066CC;
  float: left;
}

<div class="content">
  <div id="div1">div1</div>
  <div id="div1">div2</div>
  <div id="div1">div3</div>
  <div id="div1">div4</div>
</div>

最佳答案

首先,您需要将white-space:nowrap应用于父级。

这通常可以解决问题,但是子级上的float会覆盖此问题。

因此,您可以将这些div设置为display:inline-block



.content {
  width: 240px;
  overflow-x: scroll;
  overflow-y: hidden;
  max-height: 100px;
  height: 100px;
  white-space: nowrap;
  font-size:0; /* remove gap between divs */
}

.content div {
  height: 300px;
  width: 100px;
  border: solid 1px #000000;
  background-color: #0066CC;
  display: inline-block;
  font-size:1rem; /* reset font size */
}

<div class="content">
  <div id="div1">div1</div>
  <div id="div2">div2</div>
  <div id="div3">div3</div>
  <div id="div4">div4</div>
</div>





或者使用Flexbox



.content {
  width: 240px;
  overflow-x: scroll;
  overflow-y: hidden;
  max-height: 100px;
  height: 100px;
  white-space: nowrap;
  display: flex;
}

.content div {
  height: 300px;
  flex: 0 0 100px;
  border: solid 1px #000000;
  background-color: #0066CC;
}

<div class="content">
  <div id="div1">div1</div>
  <div id="div2">div2</div>
  <div id="div3">div3</div>
  <div id="div4">div4</div>
</div>

09-25 17:11