相对和绝对定位混乱 [英] Relative and absolute positioning confusion

查看:103
本文介绍了相对和绝对定位混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是html / css的新手,我刚刚开始全神贯注于定位,但似乎有些误会。现在,我正在尝试创建一个页面标题,该页面标题的下方是水平分隔线。我的标头放置在绝对位置,顶部和左侧的值为0,高度为88。我认为,如果我给定水平分隔线位置:相对,高度为5,它将最终位于标头下方。相反,它最终显示在页面的顶部,我对原因感到困惑。

I'm new to html/css and I've just started wrapping my head around positioning but I seem to have a misunderstanding. Right now I'm trying to create a page header with a horizontal divider right below it. My header is positioned absolutely, with a top and left value of 0, and a height of 88. I thought that if I gave my horizontal divider position: relative, and a height of 5, it would end up right below my header. Instead, it's ending up at the very top of the page, and I'm confused as to why.

我想在页脚上方的页面上再次使用此水平分隔线,所以我不想给此水平分隔线位置:绝对顶部:88px 。感谢所有帮助,非常感谢!

I would like to use this horizontal divider again on my page, right above my footer, so I don't want to give this horizontal divider position: absolute and top: 88px. Any help is appreciated, thanks so much!

到目前为止,我的代码(非常简单):

My (very simple) code so far:

<div id="header"></div>
  <div class="horizontal-divider"></div>

#header {
  position: absolute;
  top: 0px;
  left: 0px;
  height: 88px;
  width: 100%;
}

.horizontal-divider {
  position: relative;
  height: 5px;
  width: 100%;
  top: 0px;
  background-color: white;
  border: 1px solid black;
}


推荐答案

使用元素绝对定位相对于其包含块的边缘。它的包含块是其最接近的祖先,该祖先的位置设置为任何非静态的内容。

Absolute positioning positions an element with respect to the edges of its containing block. Its containing block is its closest ancestor that has position set to anything that isn't static. It also takes the element out of normal flow, so it doesn't influence the position of anything that follows it.

相对定位相对于元素将要定位的位置来定位元素。

Relative positioning positions an element with respect to where it would be positioned if it was position: static (not with respect to any other element).

因为#header是,所以如果它是 position:static (不针对任何其他元素)则被定位。绝对定位, .horizo​​ntal-divider 不在之后

Since #header is absolutely positioned, .horizontal-divider is not positioned after it.

如果想要立即在绝对定位的元素之后呈现元素,则:

If you want an element to be rendered immediately after an absolutely positioned element, then:


  1. 不要绝对定位第一个元素

  2. 将两个元素都放置在另一个(容器)元素中(以便它们在正常流程中一个接一个地放置)

  3. 绝对放置容器元素

也就是说,通过设置 border-bottom ,您应该能够获得想要的效果在标题上并完全删除分隔线。

That said, you should be able to get the effect you are after by setting border-bottom on the header and removing the divider entirely.

这篇关于相对和绝对定位混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆