In CSS, margin is the space around an element, outside of its border.
It defines the empty space between adjacent elements or between an element and its container's edge.
Margins do not have a background color and do not contain any content.
We can set different margins for each side of an element using the "margin-top", "margin-right", "margin-bottom", and "margin-left" properties.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> /* Different margin for each side */ .box { border: 1px solid red; } h6 { margin-top: 20px; margin-right: 10px; margin-bottom: 30px; margin-left: 15px; border: 1px solid blue; } </style> </head> <body> <div class="box"> <h6>H6 In Box with margin. h6 wrapped inside box div element</h6> </div> </body> </html>
H6 In Box with margin. h6 wrapped inside box div element
/* Different margin for each side */ h6 { margin-top: 20px; margin-right: 10px; margin-bottom: 30px; margin-left: 15px; }
H5 In Box without margin. h5 wrapped inside box div element
/* Apply 20px margin to all sides of an element */ h6 { margin: 20px; }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> /* Different margin for each side */ .box { border: 1px solid red; } h5 { border: 2px solid black; } </style> </head> <body> <div class="box"> <h5>H5 In Box without margin. h5 wrapped inside box div element</h6> </div> </body> </html>
/* Shorthand for margin */ div { margin: 10px 20px 15px 30px; /* top, right, bottom, left */ }
/* Auto margin for centering */ h6 { margin-left: auto; margin-right: auto; }
We can set the margin for all sides of an element using the margin property.
We can use the shorthand margin property to specify margins for all sides in a single declaration.
We can use the value auto to automatically calculate the margin for an element, which can be useful for centering elements horizontally.
Margins are commonly used in CSS for layout purposes to create spacing between elements, to center elements horizontally or vertically, or to control the distance between an element and its container's edge.
It's important to understand how margins interact with other layout properties like padding, border, and width, as they can affect the overall layout of a webpage.