From the course: CSS Essential Training

Unlock this course with a free trial

Join today to access over 25,500 courses taught by industry experts.

Center-aligning with margin

Center-aligning with margin

- [Instructor] So far, we've talked about using margin to set the space around an element, but we can also use margin to center align block elements on a page. Here's how. The first thing we'll need to do is to define a width for the element. I'll set it to 400 pixels. It can be any value as long as it's smaller than the viewport width. If the element spans all the way across, then there would be no need to center align it. Now let's add the margin property with two values. The first value sets the top and bottom margin. If you don't wanna add any additional space, then set it to zero. The second value will set the left and right margins. So let's add a space and then the keyword auto, end it with a semicolon. The left and right margins will now split the remaining horizontal space evenly, centering the element on the page. Now, you might be thinking, "If I set all four sides to auto with one value, this should center align…

Contents