I want to place a box and text within this box over an image.

I've managed to place text over the image as you can see on the screenshot below: enter image description here

By using this code:

#wrap {
    position:relative; 
    width: 200px;  
    height: 145px;
    border: 1px solid grey
}



#text {
z-index:100;
    position:absolute;    
    color:black;
    font-size:20px;
    font-weight:bold;
    left:10px;
    top:115px;
}

And then calling the function like this:

<div id="wrap">
    <img src="/wp-content/uploads/2014/03/brandslang.png"/>
    <div id="text">Brand</div>
</div>

I'd like to add a box around the text like this:

enter image description here

I will of course have to change the text color to white etc. And my idea was to have the text box black and then change the opacity of the box to make it see thru like that.

However I'm not sure how to add this box, I tried setting the background of the #text to black however that didn't work to well as it ended up only painting a box around the text. Also I'm not sure how I would be able to change the texts position using that option.

So this is where I was hoping you guys could help me! :)

有帮助吗?

解决方案

Since you are using position absolute you could try something like this :

#text {
    z-index: 100;
    position: absolute;    
    color: white;
    font-size: 20px;
    font-weight: bold;
    padding: 10px;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0,0,0,.4);
}

An example : http://jsfiddle.net/hQc3F/

其他提示

First I'd change all the div id's to classes so you can re-use your code throughout the page and make it more flexible.

@srekoble's answer is really good but I might do something like this.

CSS:

.wrap {
    position:relative; 
    width: 200px;  
    height: 145px;
    border: 1px solid grey;
}
.backbox {
    z-index:100;
    position:absolute;
    min-height: 30px;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0,0,0,.7);    
}
.text {
    z-index:999;
    color:#fff;
    font-size:20px;
    font-weight:bold;
}

HTML:

<div id="wrap">
    <img src="/wp-content/uploads/2014/03/brandslang.png"/>
    <div id="text">Brand</div>
</div>

http://jsfiddle.net/JtLbB/

This example allows you to style your text and background boxes differently and by using CSS classes you can apply it to more boxes throughout the site. ID's should always be unique.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top