omri
omri

Reputation: 615

Text over image without absolute position

I am trying to put some text over an image in the middle of a page.

I saw an example like this:

<img src="image.png" style="z-index: -1;" />
<p style="position: absolute; top: 1px; left: 1px;>text</p>

but when i try to center it the text will not be in the center.

<div>
    <center>
         <img src="image.png" style="z-index: -1;" />
         <p style="position: absolute; top: 1px; left: 1px;>text</p>
    </center>
</div>

How can i create a text over image without absolute possition?

Upvotes: 0

Views: 6188

Answers (2)

Guffa
Guffa

Reputation: 700442

The problem is not the absolute positioning, it's how you center the text. The text in the paragraph will be centered, but that has no effect as the paragraph has the same width as the text. When you make the paragraph absolutely positioned it no longer gets its width from its parent.

You can make the parent the same width as the image, and the paragraph the same width as the parent, and then center the text inside the paragraph. Example:

div {
  position: relative;
  width: 300px;
}

p {
  position: absolute;
  left: 0;
  bottom: 20px;
  width: 100%;
  text-align: center;
  color: #fff;
}
<div>
  <img src="http://placekitten.com/300/200">
  <p>text</p>
</div>

Demo: http://jsfiddle.net/crp6V/

Note: The position: relative; on the parent element makes it the origin for the absolute position of the paragraph.

If you want to center both the image and the text, then you would just make the paragraph the same width as the parent: http://jsfiddle.net/crp6V/2/

Upvotes: 2

Mathijs Segers
Mathijs Segers

Reputation: 6238

What you could do, is ofcourse set image as paragraph background.

if you know the exact size of the paragraph and if it's defined:

p.overlay {
    display:block;
    position:relative;
    height:40px;
    margin-top:-40px;
}

Keep the z-index and such as before, and for example this could work. An other thing, is because the p will not be centered due to being absolutely positioned, but if the parent is relative and the image has the full width of the parent, you could make the paragraph display as block, 100% width, and then center the text.

   p.overlay {
        display:block;
        position:absolute;
        width:100%;
        text-align:center
    }

So absolute position could still work

Upvotes: 0

Related Questions