Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS

Centering text

I have centered the text in the middle of the screen. But why "width: 100%" makes it in the middle and not "width: 50%" (like with top: 50%;). Were does the 100% come from? Why "top: 50%; " = middle and width: "50%" not?

.midtext {
    position: absolute;
    text-align: center;
    top: 50%;
    width: 100%;
<div class="midtext">TEXT</div>

1 Answer

rydavim
rydavim
18,813 Points

You're defining the width of the div, and then centering the text inside of the div. Think of the div as a box inside your webpage. If you define the width as 50%, the text will be centered inside the div, but the div will only be covering half the page.

If that's still confusing, try adding a border to your div. That way you can visually see its size and positioning.

.midtext {
    position: absolute;
    text-align: center;
    top: 50%;
    width: 50%;
    border: 1px solid black;
}