How to set Border, Margins and Padding in CSS

If you want to understand, what is Border, Margin or Padding in CSS, visit another post, “Understanding difference between Margin and Padding in CSS”

Example without any border/padding/margin

<!DOCTYPE html>
<html>
 
<head>
    <meta charset="UTF-8">
    <title>Understanding between Margin and Padding using css</title>
</head>
 
<body>
    <h3>This is a heading 1.</h3>
    <h3>This is a heading 2.</h3>
</body>
 
</html>

If we open this html page in browser, the two title/heading we tried to display would look like as below,

Now, lets add a simple border to this text element as,

<!DOCTYPE html>
<html>
 
<head>
    <meta charset="UTF-8">
    <title>Understanding between Margin and Padding using css</title>
    <style>
        h3 {
            border: 3px solid black;
        }
    </style>
</head>
 
<body>
 
    <h3>This is a heading 1.</h3>
    <h3>This is a heading 2.</h3>
 
</body>
 
</html>

If we open this code in browse, this will look like as below,

Now, lets try to add Margin using css as,

<!DOCTYPE html>
<html>
 
<head>
    <meta charset="UTF-8">
    <title>Understanding between Margin and Padding using css</title>
    <style>
        h3 {
            border: 3px solid black;
            margin: 40px;
        }
    </style>
</head>
 
<body>
 
    <h3>This is a heading 1.</h3>
    <h3>This is a heading 2.</h3>
 
</body>
 
</html>

The browser look of this page will look as,

50px margin around all sides of border

As we can see above 50px margin will be added on all sides of the border, and the distance between two boxes ( margin ) will be increased, where as distance between text and border (padding) remains same.

Now, lets understand the effect of adding “padding”

<!DOCTYPE html>
<html>
 
<head>
    <meta charset="UTF-8">
    <title>Understanding between Margin and Padding using css</title>
    <style>
        h3 {
            border: 3px solid black;
            margin: 40px;
            padding: 40px;
        }
    </style>
</head>
 
<body>
 
    <h3>This is a heading 1.</h3>
    <h3>This is a heading 2.</h3>
 
</body>
 
</html>

If we open this code in browser, this will look like as below,

Note: following individual properties can be twicked to change the look of any single side,

  • Margin properties: ‘margin-top’, ‘margin-right’, ‘margin-bottom’, ‘margin-left’, and ‘margin’
  • Padding properties: ‘padding-top’, ‘padding-right’, ‘padding-bottom’, ‘padding-left’, and ‘padding’
  • Border properties: ‘border-top’, ‘border-right’, ‘border-bottom’, ‘border-left’, and ‘border’


Follow Lynxbee

Leave a Reply / Ask Question