如何为子元素设置相同的顶部位置

How to set the same of top position for child elements

我有下面的代码。我不知道为什么2块中div1的顶部位置不一样。如果 child1 中的 div1 包含文本或其他元素,则 div1 和 div2、div3 的顶部位置相等。请告诉我原因。非常感谢。

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<style>
* {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>

<div id='parent' style='width: 100%;height:100%;background-color:blue;position:absolute;'>

<div id='child1' style='margin:auto auto;background-color:red;margin:10px;padding:10px;'>
  <div id='div1' style='width:50px;height:30px;background-color:grey;display:inline-block;'></div>
    <div id='div2' style='width:200px;height:30px;background-color:green;display:inline-block;'>
      <input type='text' value='Text' />
    </div>
  <div id='div3' style='width:50px;height:30px;background-color:green;display:inline-block;'>Text</div>
</div>

<div id='child2' style='margin:auto auto;background-color:red;margin:10px;padding:10px;'>
  <div id='div1' style='width:50px;height:30px;background-color:grey;display:inline-block;'>Text</div>
    <div id='div2' style='width:200px;height:30px;background-color:green;display:inline-block;'>
      <input type='text' value='Text' />
    </div>
  <div id='div3' style='width:50px;height:30px;background-color:green;display:inline-block;'>Text</div>
</div>

</div>

</body>
</html>

浏览器将没有内容或文本的 DIV 视为图像 因此它们与基线对齐,但如果 DIV 有内容,则内容本身与基线和容器对齐自动调整。

要解决此问题,您可以在您的容器上创建一个 class child 并在其第一个 div.

上使用 vertical-align:bottom;
.child>div:first-of-type {
   vertical-align: bottom;
}

见下文;

<!DOCTYPE html>
<html>

<head>
  <title>Page Title</title>
  <style>
    * {
      margin: 0px;
      padding: 0px;
    }
    
    .child>div:first-of-type {
      vertical-align: bottom;
    }
  </style>
</head>

<body>

  <div id='parent' style='width: 100%;height:100%;background-color:blue;position:absolute;'>

    <div id='child1' class="child" style='margin:auto auto;background-color:red;margin:10px;padding:10px;'>
      <div style='width:50px;height:30px;background-color:grey;display:inline-block;'></div>
      <div style='width:200px;height:30px;background-color:green;display:inline-block;'>
        <input type='text' value='Text' />
      </div>
      <div style='width:50px;height:30px;background-color:green;display:inline-block;'>Text</div>
    </div>

    <div id='child2' class="child" style='margin:auto auto;background-color:red;margin:10px;padding:10px;'>
      <div style='width:50px;height:30px;background-color:grey;display:inline-block;'>Text</div>
      <div style='width:200px;height:30px;background-color:green;display:inline-block;'>
        <input type='text' value='Text' />
      </div>
      <div style='width:50px;height:30px;background-color:green;display:inline-block;'>Text</div>
    </div>

  </div>

</body>

</html>