padding
property allows us to control the internal space between the contents and the borders.
To be more specific about the amount of padding on each side of content, we can use the following properties:
This code sets the padding-bottom to 10px.
p {
padding-bottom: 10px;
}
This code sets the paragraph padding to 10 pixels on the top and bottom and 20 pixels on the left and right.
p {
padding: 10px 20px;
}
margin
property allows us to specify the margin or space outside the element border.
The following code will set the margin of all sides to 10px;
p {
margin: 10px;
}
p {
border: 4px solid gray;
margin-top: 15px;
}
p {
margin: 5px 10px 3px 15px;
}
p {
margin: 30px 20px;
}
This code will set the p top and bottom margins to 30 pixels and the left and right margins to 20 pixels.
auto
for both margin left and rightdiv {
margin: 0 auto;
}
auto
value adjusts the left and right margins until the element is centered within its containing element.Block-level elements can have a margin around the elements, but inline elements can only have a margin to the left and right of the element.
By default, the width and height of an element are calculated:
The box-sizing
property allows us to include the padding and border in an element’s total width and height.
Example: In this code, the max-width is 100% inclusive of the padding
main {
max-width: 100%;
width: 1200px;
padding: 0 20px;
box-sizing: border-box;
}
HTML is made of inline and block-level elements.
The difference is how they’re displayed in the browser and how much room they take on the page.
The browser will automatically add display: block;
to these elements.
h2 {
display: block;
}
When we set inline-block
to an element, it still lines up next to other elements and is similar to block-level elements in terms of margin and padding.
So, we can add margin-top and margin-bottom, and padding is going to work better.
span {
display: inline-block;
}