【问题标题】:CSS creating nested div box for parent div causes overlapping [duplicate]CSS为父div创建嵌套div框导致重叠[重复]
【发布时间】:2020-05-29 01:48:51
【问题描述】:

我想在我正在开发的网站上创建一个栏以沿着框的顶部显示。

这是期望的结果

这是我的代码,我不断得到这个重叠

.page {
  display: flex;
  flex-wrap: wrap;
  position: relative;
}

.section {
  border: 2px solid #FBA7FF;
  width: 85%;
  height: 30%;
  margin: 1vw;
  padding: 1vw;
  display: flex;
  align-items: center;
  position: relative;
  z-index: 1;
}

.section h1 {
  position: relative;
}

.section_header {
  border: 4px solid #FBA7FF;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  bottom: 95%;
}
<div class='page'>
  <div class='section'>
    <div class="section_header"></div>
    <h1>sample text</h1>
  </div>
</div>

到目前为止,我已经获得了具有 position: relative 的父 div 和具有 position: absolute 的子元素,然后将顶部和左侧设置为 0 宽度到 100% 和底部到 95% 以尝试所需的效果,但它会产生重叠.

我可以看到 0 在 div 内,并且没有考虑边框,这可能就是发生这种情况的原因。

【问题讨论】:

  • 你为什么要绝对定位标题? - 删除它并尝试使用flex-direction:column
  • 使子元素定位到父元素的左中,使用绝对作为父元素设置为相对。

标签: html css


【解决方案1】:

 * {
    box-sizing: border-box;
    margin: 0;
}
        .page {
  display: flex;
  flex-wrap: wrap;
  position: relative;
}
.section {
    width: 100%;
    display: inline-block;
    text-align: center;
}
.section_header {
    width: 100%;
    background: #FBA7FF;
    display: block;
    height: 70px;
    margin-bottom: 20px;
}
<div class='page'>
        <div class='section'>
          <div class="section_header"></div>
            <h1>sample text</h1>
          </div>
      </div>

【讨论】:

  • 添加 * 框大小有效,您能解释一下原因吗?
【解决方案2】:

删除position:absolute 并使用flex-direction:column;

* {
  margin: 0;
  padding: 0;
}

.page {
  display: flex;
  flex-wrap: wrap;
  flex-direction: column;
  min-height: 100vh;
  background: lightgrey;
  position: relative;
}

.section {
  border: 2px solid #FBA7FF;
  width: 85%;
  margin: 1vh auto;
  height: 30%;
  background: lightgreen;
  display: flex;
  flex-direction: column;
  flex: 1;
  align-items: center;
}

.section_header {
  height: 50px;
  width: 100%;
  background: orange;
}
<div class='page'>
  <div class='section'>
    <div class="section_header"></div>
    <h1>sample text</h1>
  </div>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-27
    • 1970-01-01
    • 2020-04-28
    • 2016-02-27
    • 1970-01-01
    • 2014-10-07
    • 1970-01-01
    • 2010-10-17
    相关资源
    最近更新 更多