将一个 div 放在文本下方

3

我的HTML代码:

<div id="backgroundH"></div>

<div id="header">
    <h2> Premium Store </h2>
</div>

我的CSS代码:

#backgroundH {
    width: 100%;
    height: 50px;
    background-color: #dddddd;
}

#header {
    top:-50px;
    color:black;   
    font-family:Courier New;
}

body {
    background-color:#cccccc;
}

为什么它不起作用?我尝试了一切。有人可以向我展示如何将该文本放在我的div上,我在这种情况下使用它作为背景吗?
它应该看起来像一个灰色的背景,在其上面有一段文字,上面写着“高级商店”。

3
你需要的是这个吗?http://jsfiddle.net/C6B4K/1/ 还是这个 http://jsfiddle.net/C6B4K/2/? - Sridhar R
如果您想将<div>块彼此叠放,可以使用定位和z-index属性进行层叠。 - AeroX
很难说你想要实现什么,但看起来最好使用简单的背景设置和可能的底部边框(以及填充)来处理。 - Jukka K. Korpela
2个回答

2
你的div顺序有误,应该像这样:

http://jsfiddle.net/mCGt8/

HTML代码:

<div id="backgroundH">        
    <div id="header">
        <h2> Premium Store </h2>
    </div>        
</div>

CSS:

#backgroundH {
  width: 100%;
  height: 50px;
  background-color: #dddddd;       
}

#header {    
  top:-50px;
  color:black;   
  font-family:Courier New;
}

body {
  background-color:#cccccc;
}

0
在文本div中,您使用了top:-50px,因此我认为您希望文本div与背景div同属于同一级别,并且您忘记了position:relative
#header {
    position: relative;
    top: -50px;
    color: black;   
    font-family: Courier New;
}

position: relative 的问题在于,在使用 top: -50px 之前,div 所占用的空间仍然存在。

因此,你有两种方法:

  1. CSS:使用 margin-top: -50px;

  2. HTML:如果可能的话,将文本 div 嵌套到背景 div 中。(首选)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接