user9708733
user9708733

Reputation: 113

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!

Upvotes: 0

Views: 1000

Answers (3)

l3fty
l3fty

Reputation: 584

Here's with a dynamic image size and wrapping element.

h1 {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  display: block;
  margin: 0;
}
.wrap {
  position: relative;
  float: left;
}
<div class="wrap">
  <h1>Loreum!</h1>
  <img src="https://picsum.photos/300/200" alt="Loreum Pics">
</div>

Upvotes: 1

Pons Purushothaman
Pons Purushothaman

Reputation: 2261

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.

Upvotes: 0

Caleb Keene
Caleb Keene

Reputation: 388

why not just put both the img and the h1 tag in an enclosing div, and then do the absolute positioning on that div - this will be more maintainable because you won't have to be setting position: absolute on multiple elements

Upvotes: 0

Related Questions