Search code examples
htmlcssoverlaytransparency

Darken image overlay and add text over it in CSS


How would I darken (add a semi-transparent overlay) and add text to this image (but centred horizontally and vertically) as below:

enter image description here

HTML

<img src="http://luxurylaunches.com/wp-content/uploads/2014/05/uber-london.jpg" id="top" data-appear-animation="fadeIn">

CSS

#top {
  width: 100%;
  height: auto;
}
body {
  margin: 0px;
}

Fiddle here: http://jsfiddle.net/6jf0nxd5/


Solution

  • To center the text horizontaly and verticaly, you will need to wrap it in a container with text-align:center;. Then you can use a pseudo element to center it verticaly. For the overlay, you can give the text container a rgba() background color that can have transparency :

    DEMO

    body {
        margin: 0px;
    }
    .wrap{
        position:relative;
    }
    .wrap img{
        width:100%;
        height:auto;
        display:block;
    }
    .text{
        position:absolute;
        top:0; left:0;
        width:100%; height:100%;
        background:rgba(255,255,255,.5);
        text-align:center;
    }
    .text:after{
        content:'';
        width:1px; height:100%;
        vertical-align:middle;
        display:inline-block;
    }
    .text span{
        display:inline-block;
        vertical-align:middle;
    }
    <div class="wrap">
        <img src="http://luxurylaunches.com/wp-content/uploads/2014/05/uber-london.jpg" id="top" data-appear-animation="fadeIn" />
        <div class="text"><span>Text over the image
            <br/>Second line</span></div>
    </div>