Объяснение ключевых слов initial, inherit, unset и revert в CSS
Хотя большинство веб-разработчиков сталкивалось с ними, весьма вероятно, что многие, даже самые опытные, не до конца их понимают.
Долгое время я знал об этих ключевых словах только то, что они используются для сброса стилей в CSS. Но если все эти ключевые слова являются своего рода сбросом, то почему их так много? Какие именно различия между ними? Я решил глубже изучить эти ключевые слова, чтобы раз и навсегда разобраться, что отличает их друг от друга.
Базовые стили для веба Скопировать ссылку
Прежде чем мы начнем разбираться с ключевыми словами, важно понять, откуда берутся базовые стили в браузере.
Начальное значение для каждого свойства в CSS Скопировать ссылку
Каждое свойство в CSS имеет начальное ( initial ) значение. Оно никак не связано с типом HTML-элемента, к которому применяется.
Пример начального значения из MDN:
Браузерные стили Скопировать ссылку
После применения начальных стилей для всех CSS-свойств браузер загружает свои стили. Эти стили не имеют ничего общего с базовыми начальными значениями CSS-свойств.
Пример браузерных стилей:

У HTML-элементов нет начальных значений для стилей! Базовые стили HTML-элемента, такого как
, например, предоставляются стилями браузера, а не начальными значениями CSS-свойств.
Теперь начнем говорить о ключевых словах.
Ключевое слово inherit Скопировать ссылку
Ключевое слово initial Скопировать ссылку
Ключевое слово unset Скопировать ссылку
Ключевое слово unset является уникальным и работает в зависимости от типа свойства. В CSS есть два типа свойств:
1. Наследуемые свойства Скопировать ссылку

2. Ненаследуемые свойства Скопировать ссылку
Все остальные свойства, которые влияют только на элемент, для которого они заданы. Это все свойства, которые не относятся к оформлению текста. Например, если вы зададите border на родительском элементе, то он не будет задан на дочернем.

Вместо сброса свойств по отдельности, к примеру:
Ключевое слово revert Скопировать ссылку
Но что, если мы хотим сбросить значение свойства до первоначально заданных браузером значений, а не до значений по умолчанию? Например, вернуть значение свойства display элемента

Таким образом, если мы хотим сбросить все стили HTML-элемента до базовых стилей браузера, мы можем сделать это так:
Заключение Скопировать ссылку
На этом всё. Надеюсь, вам понравилась эта статья, и вы чему-то научились из моего опыта.
Видео доклада по теме Скопировать ссылку
Я сделал короткий доклад на эту тему, смотрите видео целиком на YouTube:
Cascade and inheritance
The aim of this lesson is to develop your understanding of some of the most fundamental concepts of CSS — the cascade, specificity, and inheritance — which control how CSS is applied to HTML and how conflicts are resolved.
While working through this lesson may seem less immediately relevant and a little more academic than some other parts of the course, an understanding of these things will save you much pain later on! We encourage you to work through this section carefully and check that you understand the concepts before moving on.
| Prerequisites: | Basic computer literacy, basic software installed, basic knowledge of working with files, HTML basics (study Introduction to HTML), and an idea of how CSS works (study CSS first steps.) |
|---|---|
| Objective: | To learn about the cascade and specificity, and how inheritance works in CSS. |
Conflicting rules
CSS stands for Cascading Style Sheets, and that first word cascading is incredibly important to understand — the way that the cascade behaves is key to understanding CSS.
At some point, you will be working on a project and you will find that the CSS you thought should be applied to an element is not working. Usually, the problem is that you have created two rules which could potentially apply to the same element. The cascade, and the closely-related concept of specificity, are mechanisms that control which rule applies when there is such a conflict. Which rule is styling your element may not be the one you expect, so you need to understand how these mechanisms work.
Also significant here is the concept of inheritance, which means that some CSS properties by default inherit values set on the current element’s parent element, and some don’t. This can also cause some behavior that you might not expect.
Let’s start by taking a quick look at the key things we are dealing with, then we’ll look at each in turn and see how they interact with each other and your CSS. This can seem like a set of tricky concepts to understand. As you get more practice writing CSS, the way it works will become more obvious to you.
The cascade
Stylesheets cascade — at a very simple level, this means that the order of CSS rules matters; when two rules apply that have equal specificity, the one that comes last in the CSS is the one that will be used.
Specificity
Specificity is how the browser decides which rule applies if multiple rules have different selectors, but could still apply to the same element. It is basically a measure of how specific a selector’s selection will be:
We’ll explain specificity scoring and other such things later on.
Inheritance
Inheritance also needs to be understood in this context — some CSS property values set on parent elements are inherited by their child elements, and some aren’t.
For example, if you set a color and font-family on an element, every element inside it will also be styled with that color and font, unless you’ve applied different color and font values directly to them.
Some properties do not inherit — for example, if you set a width of 50% on an element, all of its descendants do not get a width of 50% of their parent’s width. If this was the case, CSS would be very frustrating to use!
Note: On MDN CSS property reference pages you can find a technical information box called Formal definition, which lists a number of data points about that property, including whether it is inherited or not. See the color property Formal definition section, for example.
Understanding how the concepts work together
These three concepts (cascade, specificity, and inheritance) together control which CSS applies to what element; in the below sections we’ll see how they work together. It can sometimes seem a little bit complicated, but you will start to remember them as you get more experienced with CSS, and you can always look up the details if you forget! Even experienced developers don’t remember all the details.
The below video shows how you can use the Firefox DevTools to inspect a page’s cascade, specificity, and more:
Understanding inheritance
Things like widths (as mentioned above), margins, padding, and borders do not inherit. If a border were to be inherited by the children of our list, every single list and list item would gain a border — probably not an effect we would ever want!
Which properties are inherited by default and which aren’t is largely down to common sense.
Controlling inheritance
CSS provides four special universal property values for controlling inheritance. Every CSS property accepts these values.
Sets the property value applied to a selected element to be the same as that of its parent element. Effectively, this «turns on inheritance».
Sets the property value applied to a selected element to the initial value of that property.
Acts like unset in many cases, however will revert the property to the browser’s default styling rather than the defaults applied to that property.
Note: See Origin of CSS declarations in Introducing the CSS Cascade for more information on each of these and how they work.
We can look at a list of links and explore how universal values work. The live example below allows you to play with the CSS and see what happens when you make changes. Playing with code really is the best way to get to grips with HTML and CSS.
Resetting all property values
Try setting the value of all to some of the other available values and observe what the difference is.
Understanding the cascade
We now understand why a paragraph nested deep in the structure of your HTML is the same color as the CSS applied to the body, and from the introductory lessons, we have an understanding of how to change the CSS applied to something at any point in the document — whether by assigning CSS to an element or creating a class. We will now take a proper look at how the cascade defines which CSS rules apply when more than one thing could style an element.
There are three factors to consider, listed here in increasing order of importance. Later ones overrule earlier ones:
We will look at these to see how browsers figure out exactly what CSS should be applied.
Source order
We have already seen how source order matters to the cascade. If you have more than one rule, which has exactly the same weight, then the one that comes last in the CSS will win. You can think of this as rules which are nearer the element itself overwriting early ones until the last one wins and gets to style the element.
Specificity
Once you understand the fact that source order matters, at some point you will run into a situation where you know that a rule comes later in the stylesheet, but an earlier, conflicting, rule is applied. This is because that earlier rule has a higher specificity — it is more specific, and therefore is being chosen by the browser as the one that should style the element.
As we saw earlier in this lesson, a class selector has more weight than an element selector, so the properties defined on the class will override those applied directly to the element.
Something to note here is that although we are thinking about selectors and the rules that are applied to the thing they select, it isn’t the entire rule which is overwritten, only the properties which are the same.
This behavior helps avoid repetition in your CSS. A common practice is to define generic styles for the basic elements, and then create classes for those which are different. For example, in the stylesheet below we have defined generic styles for level 2 headings, and then created some classes which change only some of the properties and values. The values defined initially are applied to all headings, then the more specific values are applied to the headings with the classes.
Let’s now have a look at how the browser will calculate specificity. We already know that an element selector has low specificity and can be overwritten by a class. Essentially a value in points is awarded to different types of selectors, and adding these up gives you the weight of that particular selector, which can then be assessed against other potential matches.
The amount of specificity a selector has is measured using four different values (or components), which can be thought of as thousands, hundreds, tens, and ones — four single digits in four columns:
, ‘ ‘), and negation pseudo-class ( :not ) have no effect on specificity.
The following table shows a few isolated examples to get you in the mood. Try going through these, and making sure you understand why they have the specificity that we have given them. We’ve not covered selectors in detail yet, but you can find details of each selector on the MDN selectors reference.
Before we move on, let’s look at an example in action.
So what’s going on here? First of all, we are only interested in the first seven rules of this example, and as you’ll notice, we have included their specificity values in a comment before each one.
Note: This has only been an approximate example for ease of understanding. In actuality, each selector type has its own level of specificity that cannot be overwritten by selectors with a lower specificity level. For example, a million class selectors combined would not be able to overwrite the rules of one id selector.
A more accurate way to evaluate specificity would be to score the specificity levels individually starting from highest and moving on to lowest when necessary. Only when there is a tie between selector scores within a specificity level do you need to evaluate the next level down; otherwise, you can disregard the lower specificity level selectors since they can never overwrite the higher specificity levels.
!important
Take a look at this example where we have two paragraphs, one of which has an ID.
Let’s walk through this to see what’s happening — try removing some of the properties to see what happens if you are finding it hard to understand:
One situation in which you may have to use it is when you are working on a CMS where you can’t edit the core CSS modules, and you really want to override a style that can’t be overridden in any other way. But really, don’t use it if you can avoid it.
The effect of CSS location
Finally, it is also useful to note that the importance of a CSS declaration depends on what stylesheet it is specified in — it is possible for users to set custom stylesheets to override the developer’s styles. For example, the user might be visually impaired, and want to set the font size on all web pages they visit to be double the normal size to allow for easier reading.
To summarize
Conflicting declarations will be applied in the following order, with later ones overriding earlier ones:
Test your skills!
We have covered a lot in this article, but can you remember the most important information? You can find some further tests to verify that you’ve retained this information before you move on — see Test your skills: the Cascade.
What’s next
If you understood most of this article, then well done — you’ve started getting familiar with the fundamental mechanics of CSS. Next up, we’ll look at selectors in detail.
If you didn’t fully understand the cascade, specificity, and inheritance, then don’t worry! This is definitely the most complicated thing we’ve covered so far in the course and is something that even professional web developers sometimes find tricky. We’d advise that you return to this article a few times as you continue through the course, and keep thinking about it.
Refer back here if you start to come across strange issues with styles not applying as expected. It could be a specificity issue.
July 14, 2021 7 min read 2124
Inheritance occurs in real life. Children inherit their parents’ features: tall parents are likely to have tall children and vice versa. Children also inherit their parents’ wealth and properties.
Inheritance in software development works the same way. In OOP languages, classes inherit their parent class’ properties and methods. This is done to stave off repeating code.
What about in CSS, the design language of the web? Inheritance happens there too. If you set a property in a parent element, the children by default inherit the properties and their values without explicitly defining the property. A property such as color is passed down to an element’s children. If an element is green, all its children turn green.
In this tutorial, we’ll focus on inheritance in CSS. We’ll demonstrate how inheritance works in CSS and review some CSS properties you can use to pass down inheritable properties to child elements.
Here’s what we’ll cover:
What is CSS inheritance?
CSS rulesets cascade down the CSS hierarchy from parent selectors to their children selectors. These CSS rulesets are inherited from their parent selectors.
The child element will naturally inherit a CSS property with its value from the parent element if the CSS property is not specified.
The output looks like this:
This inheritance goes up to the closest parent element:
Which CSS properties are inherited?
Though not all CSS rules/properties are inherited, all font-* properties are inherited. This includes:
The color property is also inherited.
Inheritance in CSS occurs when an inheritable property is not set on an element. It goes up in its parent chain to set the property value to its parent value.
When you set inherit on a CSS property, the property takes the value from the element’s parent.
This applies not only to inheritable properties, but to all CSS properties.
Let’s say we have the following:
Only direct child elements can inherit a CSS property from its parent element using the inherit value if the CSS property is set by the element’s parent element. This is to ensure that the CSS property to be inherited is an inheritable property.
CSS won’t travel up div1ChildChild parent’s chain (grandparent, great-grandparent, great-great-grandparent, etc.) to check whether any a has height property set for div1ChildChild from.
So div1ChildChild won’t have a height of 100px ; instead, it will resort to its browser computed height.
initial
initial Sets the property value applied to a selected element to be the same as the value set for that property on that element in the browser’s default style sheet. If no value is set by the browser’s default style sheet and the property is naturally inherited, then the property value is set to inherit instead.
initial is a CSS property value that is used to set the initial value of a CSS property of an element. This becomes the default value of the CSS property. Each CSS property has a default value for when there is no value explicitly assigned to it.
Here’s an example without initial :
Below is an example with initial ;
The initial value of the color CSS property is black. If the color property is not specified, the color of an element text node becomes black.
Below is an example with the color value:
Here’s an example with color: initial :
unset
The unset property works on both the inherited and noninherited nature of CSS properties.
Inherited properties
If we set a color on the html element to green, it will cascade down to all the children of the html element so the whole page will have a text color of green.
Noninherited properties
These are properties that are not inherited or computed from the element’s parent. Its value is explicitly set or by its initial value. Most CSS properties that affect the element node are noninherited properties
The unset value works differently on inherited and noninherited CSS properties. When the unset value is set on an inherited property, it resets the property value to its inherited value. The unset value resets a noninherited property to its initial value.
Below is an example of u«nset in an inherited property:
Here’s an example of unset on noninherited properties:
So the unset value works on noninherited properties just like the initial value.
revert
We’ve discussed CSS base styles and browser user-agent styles. CSS base styles are default values of CSS properties. These are the natural default values that come with the properties.
Browser user-agent styles are the values set by the browser. When a page loads, the browser has its styling for some CSS properties.
Conclusion
Is your frontend hogging your users’ CPU?
LogRocket is like a DVR for web apps, recording everything that happens in your web app or site. Instead of guessing why problems happen, you can aggregate and report on key frontend performance metrics, replay user sessions along with application state, log network requests, and automatically surface all errors.
Modernize how you debug web apps — Start monitoring for free.
Understanding the “Initial”, “Inherit” and “Unset” CSS Keywords
Jan 20, 2020 · 7 min read
There’s a good chance that although most web developers have encountered them, many of even the most experienced ones don’t fully understand them.
For a long time, the only thing I knew about these k eywords was that they’re used for resetting styles in CSS. But if all of those keywords are a kind of reset, then why are there so many? What exactly are the differences between them? I decided to explore these three keywords deeply, to fully understand, once and for all, the differences between these three common keywords values.
The Basic Styles of the Web
Before we start to understand the CSS keywords, it’s important to understand from where we get our basic styles in our browser.
The Initial Value of Every Property in CSS
Every property of CSS has an initial value. This initial value has no connection to the type of HTML element it’s applied to.
An example from MDN of the initial value:
The User-Agent Browser Styles
After applying the initial styles of all the CSS properties, the browser loads its styles. These styles have nothing to do with the base initial values of the CSS properties.
An example of user-agent style:
HTML elements do not have initial style values! The basic styles of an HTML element, such as the
tag for example, comes from the browser user agent stylesheet, and not from the initial value of the properties of CSS.
Now let’s start talking about the CSS keywords!
The Inherit Keyword
The keyword value of inherit tells the browser to search for the closest parent element’s value and let the current element inherit that value. If the closest parent has an inherit value too, the browser will continue going up the DOM until it finds some value. If there isn’t any value, the browser will use its user-agent style, and if there isn’t any user-agent style, it will use the initial base style.
CSS Initial Keyword
To understand the initial keyword, we have to remember an important fact: Every property in CSS has a default value, which has nothing to do with the user agent’s default value. User-agent styles are the basic styles that the browser applies to HTML elements in the browser. We tend to think that they come automatically with the HTML, but they don’t.
The initial keyword tells the browser to use the CSS default value of the given property. For example:
The Unset Keyword
The unset keyword is unique in that it works differently on different types of properties. In CSS, there are two types of properties:
The unset value works the same as inherit for inherited properties types. For example, for the text color property, it will work like inherit value, that is, look for a parent element with a definition to the property, and if none is found — use the user-agent value, and if there isn’t any user-agent style, it will use the initial base style.
Why Use Unset if it Works Exactly the Same as Inherit and Initial?
If we’re resetting only one property, then unset is unnecessary: we can just use the inherit or initial values instead.
But nowadays we have a new property called all which brings with it a new capability: to reset both all of the inherited properties and the non-inherited properties at once!
In this new way, you don’t need to reset properties one by one. Thus, Applying the unset value to the all property will reset all the inherited properties to inherit and all of the non-inherited properties to initial.
This is the only reason for the existence of the new unset keyword value! Otherwise, we could use the inherit and initial values instead.
Instead of resetting properties one by one, for example:
We can use the new all property with the unset value, which will affect all the existing properties, for example:
The Revert Keyword
But what if we want to reset the property’s styles to its original user agent style and not to the property’s base style? For example, to revert the display property of a
This way if we want to reset all styles of an HTML tag to the browser’s base style, we can do it like this:
Browser Support
* updated in 29/4/2021
Final Words
That’s all.
I hope you’ve enjoyed this article and learned from my experience.
If you like this post, I would appreciate applause and sharing 🙂
You can follow me via Twitter.
Video Talk on This Subject:
I did a lightning talk on this subject, you can watch the full YouTube video:















