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 CSS Layout Basics Getting Started with CSS Layout Layout Wrapper Challenge

Hussain Tamboli
Hussain Tamboli
4,470 Points

How to center the div using margin-left and margin-right?

As the Challenge said set the width of the wrapper to 80%, to center the wrapper I used 10% margin-left and margin-right. Which is apparently incorrect.

Please help me understand.

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Getting Started with CSS Layout</title>
    <link href='https://fonts.googleapis.com/css?family=Varela+Round' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="page.css">
    <link rel="stylesheet" href="style.css">
</head>
    <body>
    <div class="container">
        <header>
            <h1>Best City Guide</h1>
        </header>

        <div class="main">
            <h2>Welcome!</h2>
            <p>Dessert toffee chocolate lollipop fruitcake cake sweet. Pudding cotton candy chocolate pudding liquorice jelly marzipan. Muffin gummies topping lollipop. Caramels chocolate cake donut liquorice.</p>
            <p>Cake sesame snaps sweet tart candy canes tiramisu I love oat cake chocolate bar. Jelly beans pastry brownie sugar plum pastry bear claw tiramisu tootsie roll.</p>
        </div>

        <footer>
            <p>&copy;2015 Residents of The Best City.</p>
        </footer>

    </div>
    </body>
</html>
style.css
/* Complete the challenge by writing CSS below */

.container {
  width: 80%;
  margin-left: ;
  margin-right: 10%;
}

1 Answer

Ryan S
Ryan S
27,276 Points

Hi Hussain,

The trick to centering a div in its parent element is to set the left and right margins to "auto". Your method works mathematically (although you are missing the margin-left value which will cause a syntax error), however "auto" is preferred because it handles the math for you. It will end up being more flexible if you want to change the width of the container later on.

Good luck.