Skip to content Skip to sidebar Skip to footer

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:

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:

HTML:

<div>
    <img src="http://placekitten.com/300/200">
    <p>text</p>
</div>

CSS:

div {
  position: relative;
  width: 300px;
}
p {
  position: absolute;
  left: 0; bottom: 20px;
  width: 100%;
  text-align: center; color: #fff;
}

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/


Solution 2:

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


Post a Comment for "Text Over Image Without Absolute Position"