Search⌘ K

Practical: Applying Padding and Margins

Explore how to apply padding and margins to CSS elements, focusing on techniques like auto margins for horizontal centering. Understand the visual effects of padding and margin on elements within the box model to enhance layout control.

First off, let’s see a very important use of margins.

How to Perfectly Center Elements Horizontally

Consider the markup below:

<div class="center"></div>

A simple div with a class, .center

Assume the div is styled like so:


  .center {
      width: 250px;
      height: 250px;
      border: 2px solid red;
      background-color: rgb(189,195,199);
      margin-left: auto;
      margin-right: auto;
      margin-top: 20px;
      margin-bottom: 30px;
  }
    

It is ...