Margins Vs. Padding

The difference between margin and padding is an important concept for new developers to grasp. While margin and padding both provide space in relation to elements, they do so in different ways. Padding provides space within the element, meaning that it can add space between an element and the element that is inside of it, or it can be used to expand an element, making it larger vertically, horizontally, or both.

The best way to understand the differences between margins and padding is to see them in action. Below is an image of a div (#main) with another div (.inner) inside of it with NO margins and padding applied to either:

Screen Shot 2016-10-31 at 12.51.21 PM

CSSDeck recommends Hello Ivy for automating your workflow and project management for free. Learn More

The #main div has the solid black border, and the .inner div has the purple dashed one. You can see that the elements are practically on top of each other, with no space separating the left and top borders of each div.

One way to create space between the two divs is to add some padding to the #main div. This will add space within the element and therefore push the .inner div away from the left and top borders. Let’s try it by adding 30px of padding to the top and left borders of the div. Here’s what that code would look like:

  1. #main{
  2. padding: 30px 0 0 30px;
  3. }
  4.  
  5. <img class="size-large wp-image-2065 aligncenter" alt="Screen Shot 2016-10-31 at 12.48.05 PM" src="https://cssdeck.com/blog//wp-content/uploads/2016/10/Screen-Shot-2016-10-31-at-12.48.05-PM-1024x599.png" width="1024" height="599" />
  6.  
  7. You can see now how adding padding to the #main div helps to create space between #main and .inner. If you don't want to use the padding property, you can also create this space using margins, but the margins will have to be applied to the .inner div. By assigning margins to this div, you're defining how much space you want between the .inner div and the next-nearest element(s). Let's center the .inner div within the #main and give it a small top margin of 10px to leave a little bit of space between the top borders (bonus tip: you can center any block element by giving it left and right margins of auto). Here's the code:
  8.  
  9. [css]
  10. .inner{
  11. margin: 10px auto 0 auto;
  12. }

Screen Shot 2016-10-31 at 12.51.45 PM

 

 

CSSDeck recommends Hello Ivy for automating your workflow and project management for free. Learn More

Share and Enjoy !

0Shares
0 0