CSS CSS Basics The Box Model Margins

Andrew Dank
Andrew Dank
Front End Web Development Techdegree Student 2,954 Points

Confusion about "margin: auto"

During the end of this video, the primary and secondary content divs were set to "margin-auto" and were centered. But the wildlife div was centered as well. Why was the wildlife div centered when it wasn't assigned a "margin: auto"? All it was assigned in style.css was "margin:105px 0 60px"

1 Answer

Jamie Reardon
Jamie Reardon
Treehouse Project Reviewer

The wildlife div is a child element of the primary.content div that has been centered. By default, a div takes up the full width of its parent container, so therefore, it appears centered because its parent has been centered and they both have a transparent background. Add a 1px red border to both the div elements to see what I mean. If the wildlife div element had a margin auto and a fixed width, it would get centered again inside of its parent.

The auto value makes the browser automatically calculate the margins for that element based on its width.