Inheritance In CSS - Internet Programming
Inheritance In CSS
CSS, or Cascading Style Sheets, allows us to style web pages. But have you ever wondered how styling a parent element affects its child elements? That’s the concept of inheritance.
First, let’s look at a simple example. Here’s an HTML file with a <div>
element containing a few paragraphs.
Now, let’s create a CSS file to style it. Like this:
Here, we’ve given the .parent
class a blue color and Arial font-family. Now, let’s see how these styles apply to the paragraphs.
You can see that both paragraphs are blue and use the Arial font-family. This is the magic of inheritance! The color and font-family of the parent element are automatically inherited by the child elements.
The benefit of inheritance is that you don’t have to repeatedly write the same properties. If you style the parent element, its effect is also visible on the child elements.
Non Inherited Properties -
However, not all properties are inherited. For example, margin
, padding
, and border
properties are not inherited. This means if you don’t explicitly define them on child elements, they won’t inherit.
Let’s look at another example where we use some non-inheritable properties.
Here we’ve given the .parent
a margin, but you can see it has no effect on the paragraphs.
Inherit Keyword -
Now, there’s another important concept called the inherit
keyword. Sometimes, you may want a specific property to inherit, so you can use the inherit
keyword for that property.
In this example, we’ve used color: inherit;
for the p
elements. This means the color of the paragraphs will be inherited from the parent.
Comments
Post a Comment