两个divs inline block,为什么他们不在一起?

问题描述 投票:10回答:4

我创建了两个div,我想让他们彼此相邻,但其中一个总是向下,即使他们有display: inline-block.What is wrong? 我不明白。

.container {
  width: 200px;
  border: 1px solid black;
}
.a {
  display: inline-block;
  background: red;
}
.b {
  width: 20px;
  display: inline-block;
  background: blue;
}
<div class="container">
  <div class="a">hello hello hello hello hello hello hello</div>
  <div class="b">aaa</div>
</div>
html css
4个回答
14
投票

问题是

在没有指定宽度的情况下,内联块的宽度由其内容自动决定。在你的例子中,红色块包含了一条长线,这使得它填满了(几乎)整个可用空间。蓝色代码块的宽度大于红色代码块所剩的空间,导致它被包裹到下一行。

NB: 在阅读我在2015年给出的建议之前,请注意,我现在可能会尝试使用flexbox来做,因为 在这个答案中,由Steve Sanders.

解决方案1:为两个元素指定宽度

在下面的片段中,两个块都被赋予了一个宽度。你可以指定一个像素宽度,因为你也知道容器的大小,但是百分比也可以,只要它们加起来是100%,而不是更多。

请注意,我也不得不修改了一下HTML,以去除它们之间的空白。这也是选择这个方案时常见的陷阱。

.container {
  width: 200px;
  border: 1px solid black;
}
.a {
  display: inline-block;
  width: 180px;
  background: red;
}
.b {
  display: inline-block;
  width: 20px;
  background: blue;
}
<div class="container">
  <div class="a">hello hello hello hello hello hello hello
  </div><div class="b">aaa</div>
</div>

解决方案2:将元素以表格单元格的形式显示在一行中

另外,你也可以让它们表现得像一个表格行。这样做的好处是,它们的高度也会相匹配,而且你可以很容易地给其中一个元素一个宽度,而另一个则没有。同时,你也不会遇到使用第一种解决方案时需要解决的元素之间的空白问题。

.container {
  width: 200px;
  border: 1px solid black;
  display: table;
}
.a {
  display: table-cell;
  background: red;
}
.b {
  width: 20px;
  display: table-cell;
  background: blue;
}
<div class="container">
  <div class="a">hello hello hello hello hello hello hello
  </div><div class="b">aaa</div>
</div>

5
投票

display:inline-block 使两个元素保持在同一行中 绰绰有余. 否则,这条线就会断掉。

有很多解决方案可以在这里工作,但让我们想得简单一些......

如果你已经为容器和 "b "div定义了一个固定的宽度,那么为什么不给 "a "div也设置一个固定的宽度呢?180px 剩余的?

.container {
  width: 200px;
  border: 1px solid black;
}
.a {
  width: 180px;
  display: inline-block;
  background: red;
}
.b {
  width: 20px;
  display: inline-block;
  background: blue;
}
<div class="container">
  <div class="a">hello hello hello hello hello hello hello</div><div class="b">aaa</div>
</div>

4
投票

你的 inline-block 如果元素有足够的内容,它们会填满整个水平空间,把其他元素推到下面。解决这个问题的一个方法是使用flexbox。

.container {
  width: 200px;
  border: 1px solid black;
  display: flex;
}
.a {
  background: red;
}
.b {
  width: 20px;
  background: blue;
}
<div class="container">
  <div class="a">hello hello hello hello hello hello hello</div>
  <div class="b">aaa</div>
</div>

0
投票

由于类'a'的div内的文本相对于div的大小来说是很大的,它占用了整个容器的宽度,通过给这个div一个固定的宽度小于容器的宽度或者通过 %,divs将适合彼此相邻。

编辑

.container {
  width: 200px;
  border: 1px solid black;
}
.a {
  display: inline-block;
  background: red;
  width:150px;
}
.b {
  width: 20px;
  display: inline-block;
  background: blue;
  vertical-align:top;
}
<div class="container">
  <div class="a">hello hello hello hello hello hello hello</div>
  <div class="b">aaa</div>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.