CSS - 绝对定位元素受同级边距影响?

问题描述 投票:0回答:2

我在这里遇到了一些 CSS 难题。看来我设法让自己处于一个元素的绝对位置受到其兄弟后代之一影响的位置。

前提是:我有一个

<header>
容器,其中有两个子元素
<span>
<div>
<header>
元素是相对定位的。
<span>
是绝对定位,
<div>
是相对定位。目标是让
<span>
绝对位于 top:0px 且
<div>
与其重叠。然而,边距似乎是由
<div>
元素的后代之一创建的。

这是我正在谈论的一个 CodePen.io 示例。

 body {
   margin: 0;
 }
 h1 {
   font-size: 2em;
   margin: .67em 0;
 }
 p,
 pre {
   margin: 1em 0;
 }
 header {
   height: auto !important;
   min-height: 265px;
   position: relative;
   width: 100%;
   max-height: 638px;
   overflow: visible;
   z-index: 1;
 }
 header > #abstract {
   padding: 0 5%;
   width: 100%;
   position: relative;
   left: 0;
   bottom: 0;
   z-index: 3;
 }
 header > span.featured-img {
   top: 0em;
   min-height: 265px;
   position: absolute;
   overflow: hidden;
   height: 100%;
   z-index: 1;
 }
<html>

<body>
  <header>
    <span class="featured-img"><img src="http://placehold.it/300x100" alt="featured image" title="{featured image}"/></span>

    <div id="abstract">
      <h1>article header h1</h1>
      <div id="meta">Published:
        <time pubdate datetime="2009-10-09">9th October, 2009</time>by <span class="author"><a href="#" rel="author">John Doe</a></span> in <span "categories">Consectetur</span>
      </div>
      <p class=>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sodales urna non odio egestas tempor. Nunc vel vehicula ante. Etiam bibendum iaculis libero, eget molestie nisl pharetra in. In semper consequat est, eu porta velit mollis nec.</p>
    </div>
  </header>
</body>

</html>

我意识到我可以通过将

<div>
的位置设置为固定或绝对位置来解决问题,但这会导致其他流量问题。

html css
2个回答
8
投票

display: inline-block;
添加到
header
元素,它应该对其进行排序。


0
投票

div 中的

<h1>
有上边距。只要摆脱它即可。
margin:0 0.67em 0

body {
  margin: 0;
}
h1 {
  font-size: 2em;
  margin: 0 0.67em 0;
}
p,
pre {
  margin: 1em 0;
}
header {
  height: auto !important;
  min-height: 265px;
  position: relative;
  width: 100%;
  max-height: 638px;
  overflow: visible;
  z-index: 1;
}
header > #abstract {
  padding: 0 5%;
  width: 100%;
  position: relative;
  left: 0;
  bottom: 0;
  z-index: 3;
}
header > span.featured-img {
  top: 0em;
  min-height: 265px;
  position: absolute;
  overflow: hidden;
  height: 100%;
  z-index: 1;
}
<header> <span class="featured-img"><img src="http://placehold.it/300x100" alt="featured image" title="{featured image}"/></span>

  <div id="abstract">
    <h1>article header h1</h1>

    <div id="meta">Published:
      <time pubdate datetime="2009-10-09">9th October, 2009</time>by <span class="author"><a href="#" rel="author">John Doe</a></span> in <span "categories">Consectetur</span>

    </div>
    <p class=>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sodales urna non odio egestas tempor. Nunc vel vehicula ante. Etiam bibendum iaculis libero, eget molestie nisl pharetra in. In semper consequat est, eu porta velit mollis nec.</p>
  </div>
</header>

© www.soinside.com 2019 - 2024. All rights reserved.