如何将这两个 div 垂直排列?

How do I line these two divs up vertically?

我有以下 HTML 标记:

<div id="pageWrapper">
  <div style="display: block; float: left; clear: left; border: 1px solid green;">
    <div style="display: inline-block; margin-top: 0; padding-top: 0; border: 1px solid red;">
      <img src="http://i.imgur.com/5OluoVs.png" height="95" width="75" /> <!-- some random image from imgur for test purposes -->
    </div>

    <div style="display: inline-block; border: 1px solid blue;">
      <h4>Main Object</h4>
      <p style="margin: 0; padding: 0;">
        Attribute 1
      </p>
      <p style="margin: 0; padding: 0;">
        Attribute 2
      </p>
      <p style="margin: 0; padding: 0;">
        Attribute 3
      </p>
    </div>    
  </div>

https://jsfiddle.net/34xfgx5b/

您会看到有 3 个 div 带边框。绿色边框包含两个子div。其中一个 div 有红色边框,另一个有蓝色边框。

我想弄清楚如何让这两个 div 都在绿色框内垂直居中对齐,这样图像垂直居中,文本垂直显示在绿色框内中心也是如此。现在,它们都卡在了底部,而且蓝色div中的文字被砸到了底部。每当我尝试调整内框的边距时,都会弄乱绿色框的格式。

我一直在尝试使用 vertical-align: middle 来实现这一点,但我无法让它为我工作。

如何让这两个内部 divs 在绿色框内垂直居中,以及让文本在蓝色框内垂直居中?如果可能的话,我想尝试将所有样式保留在 HTML 中,因为在实际实现中这需要一个文件。

你可以使用 Flexbox

#div1 {
  border: 1px solid green;
  display: flex;
  justify-content: center; /* ALIGN TO THE CENTER HORIZONTALLY */
  align-items: center; /* ALIGN TO THE CENTER VERTICALLY*/
}

#div2 {
  margin-top: 0;
  padding-top: 0;
  border: 1px solid red;
}

#div3 {
  border: 1px solid blue;
}
<div id="pageWrapper">
  <div id="div1">
    <div id="div2">
      <img src="http://i.imgur.com/5OluoVs.png" height="95" width="75" />
      <!-- some random image from imgur for test purposes -->
    </div>

    <div id="div3">
      <h4>Main Object</h4>
      <p style="margin: 0; padding: 0;">
        Attribute 1
      </p>
      <p style="margin: 0; padding: 0;">
        Attribute 2
      </p>
      <p style="margin: 0; padding: 0;">
        Attribute 3
      </p>
    </div>
  </div>
</div>

使用 Flexbox :)

我整理了你的代码,将 class 拆分出来:

你的HTML:

<div id="pageWrapper">
  <div class="green">
    <div class="red">
      <img src="http://i.imgur.com/5OluoVs.png" height="95" width="75" /> <!-- some random image from imgur for test purposes -->
    </div>

    <div class="blue">
        <h4 class="title">Main Object</h4>
        <p class="pg">
          Attribute 1
        </p>
        <p class="pg">
          Attribute 2
        </p>
        <p class="pg">
          Attribute 3
        </p>
    </div>    
  </div>
</div>

你的CSS:

.green {
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px 
  solid green;
}

.red {
  border: 1px solid red;
}

.blue {
  border: 1px solid blue;
}

.title {
  margin: 0;
}

.pg {
  margin: 0; 
  padding: 0;
}

如果您使用 class 标题,这会删除您的 H4 边距,那么您会看到您的文本也使用 flexbox 居中。