Why Does The Margin From An Inline-Block Element Affect A Sibling Inline-Block Element

▼魔方 西西 提交于 2021-02-05 09:17:06

问题


I can't figure out why the margin-top of the <nav> element ( which comes after the <hgroup> element ) affects the margin-top or the placement of the <hgroup> . By adding a top margin to the <nav> element, the <hgroup> element also moves down as if it also has a top-margin applied to it

heading {
  position: relative;
  display: inline-block;
  border: 1px solid #333;
}

heading hgroup {
  display: inline-block;
  font-family: "Avenir";
  font-size: 5em;
  border: 1px solid yellow;
}

nav {
  position: relative;
  display: inline-block;
  margin: 500px 0 0 -1.618em;
  border: 1px solid red;
}
<heading>
  <hgroup>
    <h1>NERD</h1>
    <h1>CO.</h1>
  </hgroup>
  <nav>
    <ul>
      <li><a href="#">articles</a></li>
      <li><a href="#">podcast</a></li>
      <li><a href="#">social</a></li>
      <li><a href="#">about</a></li>
      <li><a href="#">contact</a></li>
    </ul>
  </nav>
</heading>

回答1:


The inline-block element behaves like an inline element in that it will be subject to positioning attributes such as line-height and vertical-align. Once you increase the margin-top of nav past 500px or so, the height of the line is larger than the height of the hgroup. The default vertical-align of baseline pushes hgroup down. In other words, the elements are positioned according to the inline flow.

Please note, in the snippet below, that when I set vertical-align to top than the hgroup is placed at the top of the line.

heading {
  position: relative;
  display: inline-block;
  border: 1px solid #333;
}

heading hgroup {
  display: inline-block;
  font-family: "Avenir";
  font-size: 5em;
  border: 1px solid yellow;
  vertical-align: top;
}

nav {
  position: relative;
  display: inline-block;
  margin: 550px 0 0 -1.618em;
  border: 1px solid red;
}
<heading>
  <hgroup>
    <h1>NERD</h1>
    <h1>CO.</h1>
  </hgroup>
  <nav>
    <ul>
      <li><a href="#">articles</a></li>
      <li><a href="#">podcast</a></li>
      <li><a href="#">social</a></li>
      <li><a href="#">about</a></li>
      <li><a href="#">contact</a></li>
    </ul>
  </nav>
</heading>


来源:https://stackoverflow.com/questions/48272683/why-does-the-margin-from-an-inline-block-element-affect-a-sibling-inline-block-e

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!