2013-08-20 103 views
32

我无法在图像上浮动div。这里是什么,我试图完成一个小提琴:http://jsfiddle.net/dChUR/在图像上浮动Div

HTML:

<div class="container"> 
    <div class="tag">Featured</div> 
    <img src="http://www.placehold.it/200x200"> 
</div> 

CSS:

.container { 
    border: 1px solid #DDDDDD; 
    width: 200px; 
    height: 200px; 
} 
.tag { 
    float: left; 
    position: relative; 
    left: 0px; 
    top: 0px; 
    z-index: 1000; 
    background-color: #92AD40; 
    padding: 5px; 
    color: #FFFFFF; 
    font-weight: bold; 
} 

在这张图片:

enter image description here

我想要“精选”框浮在图像的顶部,但它似乎“清除”浮动并导致图像换行到下一行,就好像它显示为块元素一样。不幸的是,我无法弄清楚我做错了什么。有任何想法吗?

+6

http://jsfiddle.net/dChUR/3/类似的东西?添加位置:相对于容器,位置:绝对框... – sinisake

回答

57

永远不会失败,一旦我把这个问题发布到SO,我会得到一些启发性的“aha”时刻并找出答案。解决办法:

HTML:

<div class="container"> 
    <div class="tag">Featured</div> 
    <img src="http://www.placehold.it/200x200"> 
</div> 

CSS:

.container { 
    border: 1px solid #DDDDDD; 
    width: 200px; 
    height: 200px; 
    position: relative; 
} 
.tag { 
    float: left; 
    position: absolute; 
    left: 0px; 
    top: 0px; 
    z-index: 1000; 
    background-color: #92AD40; 
    padding: 5px; 
    color: #FFFFFF; 
    font-weight: bold; 
} 

的关键是,该容器具有被定位相对和标签定位绝对

+2

嘿我想做同样的事情,也使div的高度是相同的图像,但高度:100%不适用于(可能是因为绝对positoining) – akabhirav

+1

说@ jeremy-harris!,就像魅力工作! –

15

更改您的定位有点:

.container { 
    border: 1px solid #DDDDDD; 
    width: 200px; 
    height: 200px; 
    position:relative; 
} 
.tag { 
    float: left; 
    position: absolute; 
    left: 0px; 
    top: 0px; 
    background-color: green; 
} 

jsFiddle example

您需要设置在容器上的相对位置,然后在内部标签div的绝对。内标签的绝对定位将相对于外部相对定位的div。你甚至不需要标签div上的z-index规则。

2

你有正确的想法。在我看来,你只需要将.tagposition:relative更改为position:absolute,并将position:relative添加到.container即可。

0

你可能会考虑使用Relative和Absolute positining。

`.container { 
position: relative; 
} 
.tag {  
position: absolute; 
}` 

我已经有测试过,如果你还希望它改变其位置使用它作为其保证金:

top: 20px;
left: 10px;

它将把它从顶部20个像素,距左侧10个像素;但如果没有必要,请留下这个。

6

其实只是增加margin-bottom:-20px;到标签类固定它。

http://jsfiddle.net/dChUR/7/

作为块元素,div的自然已经确定的边界,他们尽量不违反。为了让它们为图像分层,因为图像没有内容,因为它们没有结束标记,你只需强迫它们做他们不想做的事情,就像违反它们的自然界限一样。

.container { 
    border: 1px solid #DDDDDD; 
    width: 200px; 
    height: 200px; 
    } 
.tag { 
    float: left; 
    position: relative; 
    left: 0px; 
    top: 0px; 
    background-color: green; 
    z-index: 1000; 
    margin-bottom: -20px; 
    } 

另一个toue采取将创建div的使用图像作为背景,然后永远放在你喜欢的地方内容。

<div id="imgContainer" style=" 
     background-image: url("foo.jpg"); 
     background-repeat: no-repeat; 
     background-size: cover; 
     -webkit-background-size: cover; 
     -mox-background-size: cover; 
     -o-background-size: cover;"> 
    <div id="theTag">BLAH BLAH BLAH</div> 
</div>