【问题标题】:A floating div and a div below an absolute positioned div leads to extra margin - why?浮动 div 和绝对定位 div 下方的 div 会导致额外的边距 - 为什么?
【发布时间】:2017-03-17 06:26:03
【问题描述】:

我在绝对定位的 div(标题)下方设置了一个左浮动 div(导航)。除了左侧浮动 div 之外,我还有另一个 div(文章),其边距略大于浮动 div 的宽度(通常用于两列布局)。导航和文章的上边距均为 4em(标题的高度为 3em) 导航 div 以 4em 的额外边距定位。我可以解决这个问题,但我的问题是:为什么要额外的保证金。 如果我省略标题的绝对定位,看起来我会期望:标题 - 边距 - 导航和文章在一行。 代码:

 * {
    box-sizing: border-box;
  }

  body { /*schalte voreinstellung Browser aus */
    margin: 0px;
    padding: 0px; 
  }
  header {
    position: absolute;
    top: 1px;
    left: 0px;
    height: 3em;
    width: 100%;
    padding: 10px;
    border: 1px solid blue;
    border-radius: 0.5em;
    background-color: silver;
  }
  nav {   
      float: left; 
      width: 17em; /*breite relativ zum Buchstaben "m" in der aktuellen Schriftgroesse */
      border: 1px dashed red; /*Rand und padding jedoch in pixel */
      margin-top: 4em;
      padding: 5px;
    }
  
  
  article {
      margin: 4em 1em 0em 18em; /* top right bottom left */
      padding: 0px 10px;
      border: 1px dashed red;
      min-width: 15em;
  }
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<title>Layout</title>
</head>
  <body>
    <header>
      headline - position fixed w&uuml;rde sie fest halten 
    </header>
    <nav>
      <h2> Navigation </h2>
      <ul>
	<li> hier die links </li>
      </ul>
    </nav>

    <article>
      <h1>CSS-basierte Layouts</h1>
      <h2>2 Spalten</h2>
      die ziemlich leer sind
    </article>

  </body>
</html>

【问题讨论】:

    标签: html css


    【解决方案1】:

    当您绝对定位标题时,布局的其余部分就像标题从未存在过一样。

    因此,在不考虑标题的情况下,我们将查看三个主要布局元素:正文、导航和文章。

    发生的情况是,由于标题现在与布局的其余部分无关,因此文章成为正文的第一个流入子项,因此它的上边距与正文的顶部边距折叠(参见 @987654321 @)。这会导致body被推下,文章的边框边缘与body齐平,看起来文章根本没有调整过。

    另一方面,导航是浮动的,因此被排除在流程之外。浮动元素的边距不会与其祖先一起折叠,因为浮动元素不在流中。所以它的边缘边缘,而不是文章的边缘边缘,与正文齐平。

    当您停止定位标题时,它仍然是正文的第一个流入子项。文章的上边距现在与标题的下边距一起折叠,而不是正文的上边距。由于标题实际上没有任何边距,并且导航和文章的顶部边距相等,这导致后两者相互对齐。

    【讨论】:

    • 是的,谢谢,这是合乎逻辑的,但我不希望当页边距折叠时主体会向下推,否则页边距将被完全忽略。设置 overflow: auto 的 body 应该避免这种行为(请参阅为什么这个 CSS margin-top 样式不起作用的链接?)但它没有。我忽略了另一个方面?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-11
    • 2011-05-17
    • 2011-04-04
    相关资源
    最近更新 更多