为什么在应用填充时 <p> 以另一个 <div> 结束,而不是扩展 div 它的位置?

Why is <p> ending up in another <div> when applying padding, instead of expanding div its in?

为什么在应用填充时 <p> 以另一个 <div> 结尾,而不是扩展 div 它的内容?

这是我的代码。最终,我试图向 <p> 元素添加一些填充以将其向下推,但在其 div 之内。

我会在右上角有一个按钮,我想要它下面的文字,但不被按钮覆盖。按钮将是 z-index:999 和相对于其 div.

的位置

编辑:这是完整代码的外观,试图包含内容。 Clearfix 在这里不起作用,按钮有 z-index:1 所以应该在最上面?

  .clearfix::after {
    display: block;
    content: "";
    clear: both;
  }
  
  .header {
    background-color: bisque;
  }
  
  .wrap {
    max-width: 960px;
  }
  
  .content h1 {
    display: inline-block;
    padding-top: 0px;
  }
  
  .content p {
    float: right;
    padding-top: 0px;
  }
  
  .button {
    background-color: red;
    position: relative;
    right: 0;
    top: 0;
    z-index: 1;
    float: right;
  }
<header class="header ">
  <div class="wrap clearfix">
    <div class="content ">
      <h1>left</h1>
      <p>right</p>
      <a href="#" class="button">button</a>
    </div>
  </div>
</header>

这是因为元素是浮动的,父元素需要"clear"浮动,这样元素就不会出现在父元素之外。您可以查阅 CSS "clearfix" 技术来清楚地说明问题和解决问题的方法。

我添加了一个新的 .clearfix class,其中包含一种流行的清除浮动子项的技术。

.clearfix::after {
  display: block;
  content: "";
  clear: both;
}

.first {
    background-color: bisque;
  }
  
  .first h1 {
    display: inline-block;
    padding-top: 10px;
  }
  
  .first p {
    float: right;
    display: inline-block;
    padding-top: 15px;
  }
  
  .second {
    background-color: grey;
  }
  
  .third {
    background-color: teal;
  }
<div class="first clearfix">
      <h1>I expand "first" div with padding</h1>
      <p>I do not expand, I am outside "first" div. End up on top of another div... Why?? </p>
    </div>
    
    <div class="second">
      <p>section 2 text</p>
    </div>
    
    <div class="third">
      <p>section 3 text</p>
    </div>
    

.first p {
  float: right;  // remove this
  display: inline-block;
  padding-top: 15px;
}

只需从您的代码中删除 float: right

你可以 google 它的 clearfix 问题。

当 child 浮动时 ​​parent 不包含它,这就是你的 p 标签消失的原因。

.cf:before,
.cf:after {
    content: " "; /* 1 */
    display: table; /* 2 */
}

.cf:after {
    clear: both;
}

.first {
    background-color: bisque;
  }
  
  .first h1 {
    display: inline-block;
    padding-top: 10px;
  }
  
  .first p {
    float: right;
    display: inline-block;
    padding-top: 15px;
  }
  
  .second {
    background-color: grey;
  }
  
  .third {
    background-color: teal;
  }
<div class="first cf">
      <h1>I expand "first" div with padding</h1>
      <p>I do not expand, I am outside "first" div. End up on top of another div... Why?? </p>
    </div>
    
    <div class="second">
      <p>section 2 text</p>
    </div>
    
    <div class="third">
      <p>section 3 text</p>
    </div>