Search code examples
htmlcssvertical-alignment

How do I apply z-index on my text to float it over my image


I am trying to float text over an image and cannot seem to get the text to sit on top of the image.

If I had an image and a text block inside a div. What CSS would be needed to make the text work as I planned.

Here is my code without the css:

<div class="row">
    <div class="text-area">
        <i class="icon ion-md-exit"></i>
        <h2>TEXT</h2>
        <p>TEXT</p>
    </div>

    <img class="bg-image" src="https://ichef.bbci.co.uk/images/ic/720x405/p0517py6.jpg">
</div>

If you could vertically align the text area too, that would be a massive help.

Thanks!


Solution

  • If I was doing this I would do it one of two ways.

    You can use the image to declare the height of the element, then place the text area over the top like this:

    <style>
    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }
    
    .row {
        width: 100%;
        margin: 0 auto;
        position: relative;
    }
    
    .text-area {
        width: auto;
        height: auto;
        position: absolute;
        top: 50%;
        left: 50%;
        -ms-transform: translate(-50%, -50%);
        -webkit-transform: translate(-50%, -50%);
        transform: translate(-50%, -50%);
        z-index: 1;
    
        text-align: center;
    }
    
    .bg-image {
        width: 100%;
        height: auto;
        margin: 0 auto;
        position: relative;
        display: block;
    }
    
    </style>
    
    <div class="row">
        <div class="text-area">
            <i class="icon ion-md-exit"></i>
            <h2>TEXT</h2>
            <p>TEXT</p>
        </div>
    
        <img class="bg-image" src="https://ichef.bbci.co.uk/images/ic/720x405/p0517py6.jpg">
    </div>
    

    Or set the height of the box and use a background image like this:

    <style>
    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }
    
    .row {
        width: 100%;
        height: 100vh;
        margin: 0 auto;
        position: relative;
    
        background-image: url(https://ichef.bbci.co.uk/images/ic/720x405/p0517py6.jpg);
        background-size: cover;
        background-position: center;
        background-repeat: no-repeat;
    }
    
    .text-area {
        width: auto;
        height: auto;
        position: absolute;
        top: 50%;
        left: 50%;
        -ms-transform: translate(-50%, -50%);
        -webkit-transform: translate(-50%, -50%);
        transform: translate(-50%, -50%);
        z-index: 1;
    
        text-align: center;
    }
    
    .bg-image {
        width: 100%;
        height: auto;
        margin: 0 auto;
        position: relative;
        display: block;
    }
    
    </style>
    
    <div class="row">
        <div class="text-area">
            <i class="icon ion-md-exit"></i>
            <h2>TEXT</h2>
            <p>TEXT</p>
        </div>
    </div>