Search code examples
csspositioncss-positionfixedabsolute

How to center text in 100% width fixed image


I have an image (picture of a lawn) styled with the following:

img{
    width: 100%;
    height: 40%;
    position: fixed; <!-- top of page-->
}

I have an <h1> Putnam Lawn Care</h1> that I would like to have overlap and be centered in the image, but am unsure how to do this with css (I have tried position:fixed; top: 20%; left: 50%; but this puts the 'P' of 'Putnam Lawn Care' at 50% so this is also not centered) ? Also I am unsure if fixed positioning is correct here, should I be using absolute? Thanks in advance for any help!


Solution

  • I hope this will work. This can place the h1 tag in 100% width and text inside that will be center aligned.

    h1{
        position:fixed; 
        top: 20%;
        width:100%;
        text align: center;
    }
    

    Since you used position:fixed for the image, it is better to use fixed position for <h1> also.This will help to stick the <h1> always with image.