Search code examples
htmlcsstextblock

How to create text block on image using just CSS


I wanted the effect from this article: http://css-tricks.com/text-blocks-over-image/

But I want to know how to do it when defining the image in CSS instead of HTML.

If I make a new line that is longer than the previous line it creates a block of background colour which is the same length as the new line, for both lines.

What's the proper way of achieving this effect (without setting up the image in HTML)?

===Additional info===

This is what I was trying earlier..

HTML:

<div class="img-main-wide">
    <span class="img-text-green">
            "be bold, and venture to be wise."<br />"Begin, be bold, and venture to be wise." 
    </span>
</div>

CSS:

.img-main-wide{
    background-image: url(../images/Pyramids-Egypt.jpg);
    max-width: 100%;
    width: 100%;
    height: 80%;
    background-size: cover;
    position: relative;
}

.img-text-green{
        position: absolute;
        margin-left: 1em;
        top: 10em;
        left: 0;
        color: white;
        padding-right: .5em;
        padding-left: .5em;
        background-color: rgba(51,102,0,0.8);
        font-size: 36px;
        font-style: oblique;

}

Solution

  • When you set position: absolute to span, you implicitly set display: block to it. So absolutely positioned span doesn't behave like text selection any more and behaves like a solid rectangle instead.

    To solve this, you can use two nested spans: the outer one for positioning and the inner one for text formatting. E.g.:

    HTML:

    <div class="img-main-wide">
        <span class="img-text-green">
            <span>
                "be bold, and venture to be wise."<br />"Begin, be bold, and venture to be wise."
            </span>
        </span>
    </div>
    

    CSS:

    /* .img-main-wide code is not changed */
    
    .img-text-green {
        position: absolute;
        margin-left: 1em;
        top: 10em;
        left: 0;
    }
        .img-text-green > span {
            color: white;
            padding-right: .5em;
            padding-left: .5em;
            background-color: rgba(51,102,0,0.8);
            font-size: 36px;
            font-style: oblique;
        }
    

    Fiddle

    Another option is just not to use position: absolute: fiddle