E. Sawyers E. Sawyers - 3 months ago 8
CSS Question

I need help adding text on top of an image

Why is this code not centering my text in the image? I have been working on this for a while, and this is about to drive me crazy. Something so simple is giving trouble.



.header-txt {
position: absolute;
left: 0;
top: 50%;
width: 100%;
text-align: center;
font-size: 5em;
}

.header-wrapper {
postion: relative;
}

.header-img {
width: 100%;
height: auto;
}

<div class="header-wrapper">
<img class="header-img" src="http://science-all.com/images/wallpapers/website-background-images/website-background-images-20.png" alt="macbook">
<div class="header-txt">Hello</div>
</div>




Answer

A couple of really simple things. First you need to forget the top:50%. When you do this the div is going to start 50% from the top and not center at 50%. So what you do is add top:0; and bottom:0;. Then you need to give your div a height. What I usually do is if it is not a dynamic height div meaning there is not going to have a lot of text and when resized in responsive design it will stay the same height, then right click on it and inspect the element to see how tall it is then you can give it the height. So your div is about 90 px tall so add a height of 90 px. Then set the vertical margin to auto so margin:auto 0; Then it should center the absolute positionded div in the relative positioned div. So your css will look like so:

.header-txt {
  position:absolute;
  top:0;bottom:0;
  margin:auto 0;
  width:100%;
  height:90px;
  font-size:5em;
  text-align:center;
}
.header-wrapper {
  position:relative;
}
.header-img {
    width: 100%;
}

If you are going to have a dynamic height div then you need to use a different technique. In this technique you will set the top and left percentages. Most people now are using the css transform property to center div's and it is a very handy technique that now has very good browser support. Here is the browser support for this technique and it is supported by most browsers now Transform property broswer support. So then your css will look like this:

.header-txt {
  position:absolute;
  left: 50%;
  top: 50%;
  -webkit-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
  font-size:5em;
}
.header-wrapper {
  position:relative;
}
.header-img {
    width: 100%;
}

Dont worry about those idiots in the comments above I feel like your question is what this forum is for and some people who frequent the site feel entitled just because they know something that you don't. I see this in a lot of questions asked on this site anymore and it really drives me crazy. You obviously tried to figure this out and just have a small question about how to finish this.

Anyway hopefully this helped.