两个div内联块,为什么它们不相邻? [英] Two divs inline block, why they are not staying next to each other?

查看:31
本文介绍了两个div内联块,为什么它们不相邻?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了两个div,我希望它们彼此相邻,但是即使显示,它们也总是掉下来:inline-block.怎么了?我不明白.

I have created two divs and I would like them to stay next to each other, but one is always going down even if they have display: inline-block. What is wrong? I don't understand.

.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>

推荐答案

问题

在不指定宽度的情况下,内联块的宽度由其内容自动确定.在您的情况下,红色块包含一长行,这使其填充(几乎)整个可用空间.蓝色块比红色块剩余的可用空间宽,从而导致其换行到下一行.

Without specifying a width, the width of the inline block is automatically determined by its contents. In your case, the red block contains a long line, which makes it fill (almost) the entire space available. The blue block is wider than the space that is left available by the red block, causing it to wrap to the next line.

注意::在阅读我在2015年提出的建议之前,请注意,我现在可能会尝试使用flexbox,例如

NB: Before reading the suggestions I gave in 2015, note that I would probably try to do it using flexbox now, as in this answer by Steve Sanders.

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

在下面的代码段中,两个块都有一个宽度.您可以指定像素宽度,因为您也知道容器的大小,但是百分比也可以使用,只要它们的总和为100%,而不是更多.

In the snippet below, both blocks are given a width. You can specify a pixel width, because you know the container size too, but percentages would work as well, provided they add up to a 100%, not more.

请注意,我也必须稍微修改HTML才能删除它们之间的空白.选择此解决方案时,这是一个常见的陷阱.

Note that I had to modify the HTML a little too to remove the whitespace between them. This is a common pitfall when choosing this solution.

.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:将元素连续显示为表格单元格

或者,您可以使它们的行为类似于表行.这样的好处是它们的高度也将匹配,并且您可以轻松地给其中一个提供宽度,而给另一个提供宽度.另外,使用第一种解决方案时,您将不会遇到需要解决的空白元素问题.

Alternatively, you can make them behave like a table row. This has the advantage that their height will match too, and that you can easily give one of them a width and the other not. Also, you won't have the whitespace-between-elements issue that you would need to solve when using the first solution.

.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>

这篇关于两个div内联块,为什么它们不相邻?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆