Twtheo
Twtheo

Reputation: 111

Align text center on top of background

I'm new to html and css, sorry if this is a "repeat" I couldn't find an answer that worked for me, but maybe I have a seperate problem. I have set a background with this CSS code here:

.background {
position: fixed;
top: -50%;
left:-50%;  
width: 200%; 
height: 200%;
}
.background img { 
position: absolute;
top: 0; 
left: 0; 
right: 0; 
bottom: 0; 
margin: auto; 
min-width: 50%;
min-height: 50%;
}

And have used it in HTML here:

<div class="background"><img src="lol_background.png" alt="League Champion Background" /></div>

Now, I'm trying to center a title on top of this background, but for some reason I cannot figure it out, my CSS for the header is here:

#headtxt {
position: absolute;
text-align: center;
margin: auto;
z-index: 100;
color: pink; 
}

And I call it in the HTML like so:

<h1 id="headtxt">Before and After: League AP Item Changes</h1>

So, here is what I've tried: When I remove position: absolute the text falls behind the background. And obviously right now, having the text-align: center; seems to be doing nothing. So I'm not exactly sure what is going on, but I assume it's some lame rookie mistake.

Upvotes: 1

Views: 50

Answers (2)

just95
just95

Reputation: 1099

The width of an element whose position property is set to absolute is determined automatically. To center the text you have to set the width of #headtext to 100%.

.background {
  position: fixed;
  top: -50%;
  left:-50%;  
  width: 200%; 
  height: 200%;
}
.background img { 
  position: absolute;
  top: 0; 
  left: 0; 
  right: 0; 
  bottom: 0; 
  margin: auto; 
  min-width: 50%;
  min-height: 50%;
}
#headtxt {
  position: absolute;
  text-align: center;
  margin: auto;
  z-index: 100;
  color: pink; 
  width: 100%;
}
<div class="background">
  <img src="http://lorempixel.com/640/480/nature" />
</div>

<h1 id="headtxt">Before and After: League AP Item Changes</h1>

Upvotes: 1

oguzhancerit
oguzhancerit

Reputation: 1572

You can use background with html tag for your background of application. You do not need other divs to place background. Try the below code.

http://codepen.io/ogzhncrt/pen/ZGZxXK

Before and After: League AP Item Changes

<style>
html { 
  background: url(http://i.imgur.com/JcWrY8U.jpg) no-repeat center center fixed; 
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

#headtxt {
  width:100%;
  text-align:center;
}
</style>

Upvotes: 0

Related Questions