In the last article, we learned about how to use borders in web pages including their styling with colors, styles and rounded corners.
The inherit Value
Now in this article, we are going to see something that confuses most of the new web developers and need to be clear as soon as possible. We are going to study margins and padding in CSS. We have already studied a little bit in HTML articles, but let's study in detail and avoid any future confusion.
Let's begin...
There are two ways in CSS to create space around elements:
margins and padding
In most usages, they give the similar output.For example, if we add 10 pixels of margin or padding to the right side of the element, that element will generally move 10 pixels to left on the screen. But in reality, they both are doing this same thing in a different way.
So let's see what actually happens behind the scenes...
CSS Margins
Basics
The margin property in CSS is used to create space around the elements outside of defined borders if any.
Actually, margin property is shortcut property for the following individual properties:
- margin-top
- margin-right
- margin-bottom
- margin-left
margin-top:10px
margin-right:20px
margin-bottom:30px
margin-left:40px.
Just remember order is important while writing in the margin which is top, right, bottom and left.
The auto Value
We can set margin property to auto to horizontally center the element within the container it is in. In this case, let's say
Total width of container = 500px;
Total width of element = 200px;
Hence, remaining space = 500 - 200 = 300px
This remaining space will be split equally between the left and right margins.
Hence left margin = right margin = 150px
If you set margin property to inherit then it will have same margin values as it's parent element.
The great phenomenon of Margin Collapse
Let's see the example:
We have two elements(say paragraphs). Set the margin-bottom of first to 60px and margin-top of the second paragraph to 30 px. Now according to our common sense, there should be space of 90px between two paragraphs. But due to Margin Collapse, the margin will be 60px only. Remember this does not happen for horizontal margins...
That's all for today. In the next part, we will study about padding in detail and will finally see when to use what.
Till then #keepCoding.
Comments
Post a Comment