John Baker
John Baker

Reputation: 435

Positioning DIVs with CSS

I have two DIVs inside each other. The inner DIV contains an image. I'm trying to add a floating text over that image in the top right corner. I can't figure out how to make that text to use inner DIV's positions instead of the outer one.

Here is what I got so far

CSS:

html {
    background: #EEF0F3;
}
.outer {
    background: #FFFFFF;
    border-radius: 4px 4px 4px 4px;
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
    margin: 0 auto;
    padding:20px 0px;
    position: relative;
    width: 680px;
    text-align: center;
    margin-bottom: 20px;
}
.inner {
    position: relative;
}
h2 { 
   position: absolute; 
   top: 0px; 
   right: 0px; 
}
h2 span { 
   color: white; 
   font: bold 24px Helvetica, Sans-Serif; 
   letter-spacing: -1px;
   background: rgba(255, 0, 0, 0.5);
   padding: 0px 10px; 
}

HTML:

<div class="outer">
    <div class="inner">
        <h2><span>Title 1</span></h2>
        <img src="1.jpg">
    </div>
</div>

And here is the code in JSFiddle

http://jsfiddle.net/UM8ea/

If I set positioning to:

h2 { 
   position: absolute; 
   top: 20px; 
   right: -20px; 
}

I get the desired result, but that feels like workaround rather than a solution.

Upvotes: 0

Views: 78

Answers (2)

Raj
Raj

Reputation: 21

Its very simple.

Check this fiddle

.outer {
background: #FFFFFF;
border-radius: 4px 4px 4px 4px;
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
margin: 0 auto;
padding:20px 0px;
position: relative;
width: 680px;
text-align: center;
margin-bottom: 20px;
}

for h2

 h2 
{ 
position: absolute; 
top: 5px; 
right: 20px; 
margin:0;
}

Upvotes: 2

Arkana
Arkana

Reputation: 2889

You have this behaviour because .outer is wider than the image, and then, .inner too. The h2 is positioned related to .inner, and go to right.

If you set .outer to have 640px width (as the image) you get the desired result.

Other solution is to set margin: 0 20px; on .inner

If you want the text positioned all top the image you can set h2 {margin:0;} in both cases.

Upvotes: 1

Related Questions