CSS margin


Margins

Margins help us to create space around elements.
Using CSS, you can completely control an element’s margins. For example, you can use the available properties to set the margin for every side of a given element. You can also use negative values while specifying the margin.

Specifying margin property:

Here are the sides for which individual properties can be applied to get margin using CSS:

  • margin-top
  • margin-right
  • margin-bottom
  • margin-left

All the above sides can have the following properties:

  • auto – Lets the browser calculate the margin.
  • length – Helps ins specifying margin in cm, px, etc.
  • % - Lets the user specify the margin in % of the width of the element.
  • inherit – It tells that the element must inherit the margin from its parent element.

Shorthand margin property:

You can also shorten the code for specifying the margin by combining them all in one statement. Here is how to do it:

  • For margin property with 4 values –margin: 25px 50px 75px 100px; Here, the top margin is of 25px, bottom of 75px, right of 50px and left of 100px.
  • For margin property with 3 values –margin: 25px 50px 75px; Here, the top margin is of 25px, right and left are of 50px and bottom is of 75px
  • For margin property with 2 values –margin: 25px 50px; Here, the top and bottom margins are of 25px and left and right are of 50px.
  • For margin property with a single value –margin: 25px; Here, all the margins are of 25px.
  • Example:

    <html> <html lang="en-US"> <style> div { border: 1px solid black; margin-top: 100px; margin-bottom: 100px; margin-right: 150px; margin-left: 80px; background-color: lightblue; } </style> </head> <body> <h2>Knowledge2life</h2> <div>Online learning website.</div> </body> </html>

    OUTPUT:

    Knowledge2life

    Online learning website.