内联块未对齐同一行

时间:2019-04-23 03:14:06

标签: html css

我将display: inline-block用于div.left-div.rightdiv.red-div.yellow,但是它们都不在同一行。我精确地设置了宽度。但这根本不起作用。

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
.container {
  margin: 0 auto;
  width: 800px;
}
.left, .right, .red, .yellow {
  display: inline-block;
  vertical-align: top;
}
.left {
  width: 250px;
  height: 500px;
  background: gray
}
.right {
  width: 550px;
  height: 550px;
  background: blue;
}
.red {
  background: red;
  width: 275px;
  height: 200px;
}
.yellow {
  background: yellow;
  width: 275px;
  height: 200px;
}
<div class="container">
  <div class="left"></div>
  <div class="right">
    <div class="red-yellow">
      <div class="red"></div>
      <div class="yellow"></div>
    </div>
  </div>
</div>

2 个答案:

答案 0 :(得分:1)

更新

如果您需要保留inline-block样式,则需要.left和。right div来总计800pxinline-block的作用是它将包含空白并将其添加到宽度中。这就是包裹仍在发生的原因。下图显示了导致包裹的空白区域。

enter image description here

many ways可以删除空格并使之适合。一种方法是在HTML.left right之间添加div注释,这将删除所有空白。

<div class="container">
  <div class="left"></div><!-- 
   --><div class="right">
    <div class="red-yellow">
      <div class="red"></div>
      <div class="yellow"></div>
    </div>
  </div>
</div>

演示

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
.container {
  margin: 0 auto;
  width: 800px;
}
.left, .right, .red, .yellow {
  display: inline-block;
  vertical-align: top;
}
.left {
  width: 250px;
  height: 500px;
  background: gray
}
.right {
  width: 550px;
  height: 550px;
  background: blue;
}
.red {
  background: red;
  width: 275px;
  height: 200px;
}
.yellow {
  background: yellow;
  width: 275px;
  height: 200px;
}
<div class="container">
  <div class="left"></div><!--
  --><div class="right">
    <div class="red-yellow">
      <div class="red"></div>
      <div class="yellow"></div>
    </div>
  </div>
</div>


如果将display: flex添加到.container,则直接子项(.left.right)将在同一行中对齐。 .right div50px .leftdiv,因为设置了显式宽度(550px.right500px代表.left)。

此外,您可以删除它,因为由于flexbox容器的影响,它不再起作用。

.left, .right, .red, .yellow {
  display: inline-block;
  vertical-align: top;
}

演示

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
.container {
  margin: 0 auto;
  width: 800px;
  display: flex;
}

.left {
  width: 250px;
  height: 500px;
  background: gray
}
.right {
  width: 550px;
  height: 550px;
  background: blue;
}
.red {
  background: red;
  width: 275px;
  height: 200px;
}
.yellow {
  background: yellow;
  width: 275px;
  height: 200px;
}
<div class="container">
  <div class="left"></div>
  <div class="right">
    <div class="red-yellow">
      <div class="red"></div>
      <div class="yellow"></div>
    </div>
  </div>
</div>

答案 1 :(得分:1)

如果使用display:inline-block,则元素之间会有一些空间。为了克服这一点,您可以使用float属性,以便每个元素都在同一行中对齐。

如果要使用display:inline-block属性,则必须减小.red和.yellow的宽度,例如

<Parent>
  <Carousel />
</Parent>