CSS Margins
css, margins, css margins, dataidea, data science, web development, website
Margins
CSS Margins create space around or outside and element.
CSS Margins - Individual Sides
The following properties set the length of the margin each side
margin-top
: sets the margin area on top of an elementmargin-right
: sets the margin area on the right of an elementmargin-bottom
: sets the margin area on the bottom side of an elementmargin-left
: sets the margin area on the left side of an element
Valid values:
<length>
<percentage>
auto
: selects a suitable margin to use. For example in certain cases this value can be used toe center an element.
Element:
Here’s an example of using margins
div {margin-top: 30px;
margin-left: 90px;
background: lightgrey;
border: 5px solid red;
width: 200px;
height: 200px;
}
Output:
Note!
The margin sorrounds a CSS box, and pushes up against other CSS boxes in the layout. You will learn about CSS box models in the next few lessons
CSS Margin - Shorthand Property
The margin
CSS property is a shorthand for the following properties
margin-top
margin-right
margin-bottom
margin-left
The margin
property can have one, two, three, or four values.
- When one value is specified, it applies the same margin to all four sides
- When two values are specified, the first value applies to the top and bottom, the second to the left and right
- When three values are specified, the first value applies to the top, the second to the left and right,the third to the bottom
- When four values are specified, the margins apply to the top, right, bottom and left in that order (clockwise) respectively.
Horizontally Centering an Element
We can center an element by setting the left and right margins to auto
.
div {margin: 0 auto;
width: 200px;
height: 200px;
border: 5px solid green;
background: lightgrey;
}
Result:
The inherit
Value
Since the inherit value is a global value, it can work on almost all the CSS properties
Below is an example of a child element inheriting margin from its parent element.
<!DOCTYPE html>
<html>
<head>
<title>DATAIDEA</title>
<style type="text/css">
#parent {
divmargin-left: 50px;
border: 5px solid green;
}
#child {
pmargin-left: inherit;
}</style>
</head>
<body>
<h3>The inherit Global Value</h3>
<div id="parent">
<p id="child">This element's left margin is inherited from the parent</p>
</div>
</body>
</html>
Result:
This element’s left margin is inherited from the parent
To be among the first to hear about future updates of the course materials, simply enter your email below, follow us on (formally Twitter), or subscribe to our YouTube channel.