绝对定位的元素落在其父容器之外

时间:2014-10-31 01:15:27

标签: html css css-position

我正在开展一个项目,我需要将上一个和下一个导航元素浮动到博客存档页面标题的两侧(本例中为绿色圆圈)。坐在绿色圆圈内将是一个带有SVG背景元素的跨度 - 因此需要定位圆圈。

我想保持语义,所以我已经按照以下方式布置了我的页面(部分)标题:

<header class="archive-box">    

    <nav class="archive-nav">

      <div class="left-nav">
        <a class="icon-bg" href="#" title="">
        </a>
      </div>

      <div class="right-nav">
        <a class="icon-bg" href="#" title="">
        </a>
      </div>

    </nav>

    <h2>Stuff and Things</h2>

</header>

CSS

.archive-box {
  max-width: 900px;
  height: 75px;
  margin: 50px auto;
  border: 1px solid;
  position: relative;
}
.archive-nav {
  position: absolute;
  top: 0;
  left: 0;
  right: 0; 
}
.left-nav {
  position: absolute;
  left: 0;
}
.right-nav {
  position: absolute;
  right: 0;
}

.icon-bg {
  background-color: #9ccb3b;
  border-radius: 50%;
  height: 75px;
  width: 75px;
  position: absolute;
}

h2 {
  text-align: center;
}

正确的导航元素位于其父容器之外。我认为这可能与我有多个父子绝对元素这一事实有关。还有另一种方法吗?

Here's the CodePen

2 个答案:

答案 0 :(得分:0)

有时您需要具有编码css位置的特定顺序。我的意思是,如果您粘贴整个代码并运行它,如果您逐步编写并保存它将会有所不同。当我学习CSS时,它帮助了我几次 同时尝试将margin:auto放入.right-nav和.left-nav

答案 1 :(得分:0)

这是你想要的吗?的 CodePen 即可。我没有使用position: absolute,而是使用float: leftfloat: right,以便leftright菜单项位于左侧,分别是右侧,标题位于中心。

&#13;
&#13;
section {
  position: relative;
  background-color: blue;
  color: white;
  width: 80%;
  margin: auto;
}
article {
  background-color: green;
  height: 50px;
}
h1 {
  color: white;
  font-size: 30px;
}
nav {
  top: 0;
  font-size: 20px;
}
.left {
  left: 0;
  /* position: absolute; */
  color: yellow;
}
.right {
  right: 0;
  /* position: absolute; */
  color: pink;
}
h1 {
  text-align: center;
}
.bg {
  float: left
}
.bgtwo {
  float: right;
}
&#13;
<section>
  <nav>
    <div class="bg">
      <div class="left">LEFT</div>
    </div>
    <div class="bgtwo">
      <div class="right">RIGHT</div>
    </div>
  </nav>
  <h1>Hello There</h1>
  <article>
    <p>Here is some stuff about things.</p>
  </article>
</section>
&#13;
&#13;
&#13;