Css значение inherit

Web Safe Colors?

Many years ago, when computers supported maximum 256 different colors, a list of 216 «Web Safe Colors» was suggested as a Web standard (reserving 40 fixed system colors).

This is not important now, since most computers can display millions of different colors.

This 216 hex values cross-browser color palette was created to ensure that all computers would display the colors correctly when running a 256 color palette:

000000 000033 000066 000099 0000CC 0000FF
003300 003333 003366 003399 0033CC 0033FF
006600 006633 006666 006699 0066CC 0066FF
009900 009933 009966 009999 0099CC 0099FF
00CC00 00CC33 00CC66 00CC99 00CCCC 00CCFF
00FF00 00FF33 00FF66 00FF99 00FFCC 00FFFF
330000 330033 330066 330099 3300CC 3300FF
333300 333333 333366 333399 3333CC 3333FF
336600 336633 336666 336699 3366CC 3366FF
339900 339933 339966 339999 3399CC 3399FF
33CC00 33CC33 33CC66 33CC99 33CCCC 33CCFF
33FF00 33FF33 33FF66 33FF99 33FFCC 33FFFF
660000 660033 660066 660099 6600CC 6600FF
663300 663333 663366 663399 6633CC 6633FF
666600 666633 666666 666699 6666CC 6666FF
669900 669933 669966 669999 6699CC 6699FF
66CC00 66CC33 66CC66 66CC99 66CCCC 66CCFF
66FF00 66FF33 66FF66 66FF99 66FFCC 66FFFF
990000 990033 990066 990099 9900CC 9900FF
993300 993333 993366 993399 9933CC 9933FF
996600 996633 996666 996699 9966CC 9966FF
999900 999933 999966 999999 9999CC 9999FF
99CC00 99CC33 99CC66 99CC99 99CCCC 99CCFF
99FF00 99FF33 99FF66 99FF99 99FFCC 99FFFF
CC0000 CC0033 CC0066 CC0099 CC00CC CC00FF
CC3300 CC3333 CC3366 CC3399 CC33CC CC33FF
CC6600 CC6633 CC6666 CC6699 CC66CC CC66FF
CC9900 CC9933 CC9966 CC9999 CC99CC CC99FF
CCCC00 CCCC33 CCCC66 CCCC99 CCCCCC CCCCFF
CCFF00 CCFF33 CCFF66 CCFF99 CCFFCC CCFFFF
FF0000 FF0033 FF0066 FF0099 FF00CC FF00FF
FF3300 FF3333 FF3366 FF3399 FF33CC FF33FF
FF6600 FF6633 FF6666 FF6699 FF66CC FF66FF
FF9900 FF9933 FF9966 FF9999 FF99CC FF99FF
FFCC00 FFCC33 FFCC66 FFCC99 FFCCCC FFCCFF
FFFF00 FFFF33 FFFF66 FFFF99 FFFFCC FFFFFF

Базовые стили для веба#

Прежде чем мы начнем разбираться с ключевыми словами, важно понять, откуда берутся базовые стили в браузере

Начальное значение для каждого свойства в CSS

Каждое свойство в CSS имеет начальное () значение. Оно никак не связано с типом HTML-элемента, к которому применяется.


Пример начального значения из MDN:

Браузерные стили

После применения начальных стилей для всех CSS-свойств браузер загружает свои стили. Эти стили не имеют ничего общего с базовыми начальными значениями CSS-свойств.

Пример браузерных стилей:

У HTML-элементов нет начальных значений для стилей! Базовые стили HTML-элемента, такого как , например, предоставляются стилями браузера, а не начальными значениями CSS-свойств.

Теперь начнем говорить о ключевых словах.

Ключевое слово initial#

Чтобы понять ключевое слово , мы должны помнить важный факт: у каждого свойства в CSS есть значение по умолчанию, которое не имеет ничего общего со значениями, которые устанавливаются браузером. Браузерные стили — это стили, которые применяются браузером к конкретным HTML-элементам. Мы часто думаем, что они автоматически приходят вместе с HTML, но это не так.

Ключевое слово говорит браузеру использовать значение по умолчанию для заданного CSS-свойства. Например, для свойства значение всегда будет .

Такое поведение может очень запутывать, потому что, как мы и говорили ранее, значение по умолчанию для CSS-свойства не всегда совпадает со значением, которое браузер задает конкретному элементу. Например, -значение для свойства равно для всех элементов. Поэтому, если для элемента будет задано свойство со значением , то свойство будет вычислено как , а не , как в стилях браузера.

Пример:

Examples of inherit in a Sentence

She inherited the family business from her father. Baldness is inherited from the mother’s side of the family. She inherited her father’s deep blue eyes. She inherited a love of baseball from her dad. When my brother left for college, I inherited his old computer. The company’s new president will inherit some complicated legal problems. When the coach quit, her assistant inherited a last-place team.

See More

Recent Examples on the Web People with the disease receive the sickle cell gene from both parents, while those who inherit the gene from just one parent are carriers of the trait. — Christopher Snowbeck, Star Tribune, «UnitedHealth Group studies COVID-19 risks with sickle cell,» 8 Aug. 2020 Jeffrie had also seen her parents’ generation struggle to inherit that dream of homeownership as the abundant urban manufacturing jobs that had lured her grandparents from the South in the Great Migration vanished. — jsonline.com, «Homeownership for Black families in Milwaukee is worse now than 50 years ago. Could a regional approach to affordable housing help?,» 7 Aug. 2020 Now, here comes Mike McCarthy, who will inherit Kellen Moore as the offensive coordinator but is expected to change things. — Calvin Watkins, Dallas News, «Questions surrounding the Cowboys: How much different will the offense look under Mike McCarthy?,» 3 Aug. 2020 The Secure Act did away with the Stretch IRA for most people who inherit a retirement account in 2020 or later. — Kathleen Pender, SFChronicle.com, «Answers to questions on IRAs, required distributions and late tax refunds,» 1 Aug. 2020 As the next in line to inherit the crown, royal heirs are entitled to a number of privileges. — Katie Frost, Redbook, «7 Things You Didn’t Know About Being a Royal Heir,» 4 Sep. 2017 That new speaker will inherit a massive fundraising problem: House Republicans will need several million dollars to elect a slate of GOP candidates this fall. — Jessie Balmert, The Enquirer, «With the imminent ouster of Speaker Householder, House GOP lost its top fundraiser,» 29 July 2020 In a sense, both were literally or figuratively blown away in the prime of life, instead of surviving to inherit the world their fathers hoped to build for them. — Andrea Wurzburger, PEOPLE.com, «10 Historical Easter Eggs from Hamilton You Might Have Missed,» 8 July 2020 Last year, Congress passed the Secure Act, which changed the rules for many people who inherit in 2020 or later. — Kathleen Pender, SFChronicle.com, «If you inherit a retirement account, make sure you read this,» 4 July 2020

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, however, 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 matter; when two rules apply that have equal specificity the one that comes last in the CSS is the one that will be used.

In the below example, we have two rules that could apply to the . The ends up being colored blue — these rules have an identical selector and therefore carry the same specificity, so the last one in the source order wins.

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:

  • An element selector is less specific — it will select all elements of that type that appear on a page — so will get a lower score.
  • A class selector is more specific — it will select only the elements on a page that have a specific attribute value — so will get a higher score.

Example time! Below we again have two rules that could apply to the . The below ends up being colored red — the class selector gives its rule a higher specificity, and so it will be applied even though the rule with the element selector appears further down in the source order.

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 and 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 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, usually at the bottom of the specifications section, which lists a number of data points about that property, including whether it is inherited or not. See the , for example.

Using DevTools to See Inherited Values


DevTools can be used to view properties that an element inherits from its parent or from another element up the DOM tree. As already mentioned, not all properties of a parent element are inheritable. Neither do all the inheritable properties make it to the end of the inheritance chain without being overridden by another CSS rule somewhere else.

DevTools gives you different visual cues to easily distinguish between all such properties, which you can see in the screenshot below, taken from SitePoint’s CSS:

Any properties that are not inheritable by the selected element are dimmed. Properties that were inheritable but were overridden are displayed with strike-through text.

Ключевое слово unset#

Ключевое слово является уникальным и работает в зависимости от типа свойства. В CSS есть два типа свойств:

1. Наследуемые свойства

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

2. Ненаследуемые свойства

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

Ключевое слово работает так же, как и  для наследуемых свойств. Например, для текстового свойства оно будет работать как значение , то есть будет искать ближайший родительский элемент с заданием нужного свойства, а если он не будет найден, то применится браузерное значение, а если и браузерных стилей нет, то применится значение .

Для ненаследуемых свойств ведет себя как , то есть применится значение по умолчанию. Например, для свойства оно будет работать как .

Зачем использовать , если оно работает так же, как и ?

Если ведет себя как и , то зачем оно может понадобиться? Если мы сбрасываем только одно свойство, то  не нужен. Вместо него мы можем просто использовать или . Но сейчас у нас есть свойство , которое дает нам новую возможность — сбросить наследуемые и ненаследуемые свойства одновременно.

Таким образом, вам не нужно сбрасывать свойства по отдельности. Применение ключевого слова к свойству приведет к сбросу всех наследуемых свойств к значению и всех ненаследуемых свойств — к значению .

Это единственная причина существования нового ключевого слова ! В противном случае мы могли бы вместо этого использовать и .

Вместо сброса свойств по отдельности, к примеру:

Мы можем использовать новое свойство со значением , которое повлияет на все существующие свойства, например:


Я создал небольшой пример для демонстрации того, как свойства ведут себя, когда используется свойство со значением . Некоторые ведут себя так, как будто к ним применено значение , а некоторые так, как будто к ним применено значение . Пример на Codepen использования .

Examples

Color value tester

In this example we provide a and a text input. Entering a valid color into the input causes the to adopt that color, allowing you to test our color values.

JavaScript

const inputElem = document.querySelector('input');
const divElem = document.querySelector('div');

function validTextColor(stringToTest) {
  if (stringToTest === "") { return false; }
  if (stringToTest === "inherit") { return false; }
  if (stringToTest === "transparent") { return false; }

  const image = document.createElement("img");
  image.style.color = "rgb(0, 0, 0)";
  image.style.color = stringToTest;
  if (image.style.color !== "rgb(0, 0, 0)") { return true; }
  image.style.color = "rgb(255, 255, 255)";
  image.style.color = stringToTest;
  return image.style.color !== "rgb(255, 255, 255)";
}

inputElem.addEventListener('change', () => {
  if(validTextColor(inputElem.value)) {
    divElem.style.backgroundColor = inputElem.value;
    divElem.textContent = '';
  } else {
    divElem.style.backgroundColor = 'white';
    divElem.textContent = 'Invalid color value';
  }
});

Result

RGB syntax variations

This example shows the many ways in which a single color can be created with the various RGB color syntaxes.

/* These syntax variations all specify the same color: a fully opaque hot pink. */

/* Hexadecimal syntax */
#f09
#F09
#ff0099
#FF0099

/* Functional syntax */
rgb(255,0,153)
rgb(255, 0, 153)
rgb(255, 0, 153.0)
rgb(100%,0%,60%)
rgb(100%, 0%, 60%)
rgb(100%, 0, 60%) /* ERROR! Don't mix numbers and percentages. */
rgb(255 0 153)

/* Hexadecimal syntax with alpha value */
#f09f
#F09F
#ff0099ff
#FF0099FF

/* Functional syntax with alpha value */
rgb(255, 0, 153, 1)
rgb(255, 0, 153, 100%)

/* Whitespace syntax */
rgb(255 0 153 / 1)
rgb(255 0 153 / 100%)

/* Functional syntax with floats value */
rgb(255, 0, 153.6, 1)
rgb(1e2, .5e1, .5e0, +.25e2%)

RGB transparency variations

/* Hexadecimal syntax */
#3a30                    /*   0% opaque green */ 
#3A3F                    /* full opaque green */ 
#33aa3300                /*   0% opaque green */ 
#33AA3380                /*  50% opaque green */ 

/* Functional syntax */
rgba(51, 170, 51, .1)    /*  10% opaque green */ 
rgba(51, 170, 51, .4)    /*  40% opaque green */ 
rgba(51, 170, 51, .7)    /*  70% opaque green */ 
rgba(51, 170, 51,  1)    /* full opaque green */ 

/* Whitespace syntax */
rgba(51 170 51 / 0.4)    /*  40% opaque green */ 
rgba(51 170 51 / 40%)    /*  40% opaque green */ 

/* Functional syntax with floats value */
rgba(255, 0, 153.6, 1)
rgba(1e2, .5e1, .5e0, +.25e2%)

HSL syntax variations

/* These examples all specify the same color: a lavender. */
hsl(270,60%,70%)
hsl(270, 60%, 70%)
hsl(270 60% 70%)
hsl(270deg, 60%, 70%)
hsl(4.71239rad, 60%, 70%)
hsl(.75turn, 60%, 70%)

/* These examples all specify the same color: a lavender that is 15% opaque. */
hsl(270, 60%, 50%, .15)
hsl(270, 60%, 50%, 15%)
hsl(270 60% 50% / .15)
hsl(270 60% 50% / 15%)
hsla(240, 100%, 50%, .05)     /*   5% opaque blue */ 
hsla(240, 100%, 50%, .4)      /*  40% opaque blue */ 
hsla(240, 100%, 50%, .7)      /*  70% opaque blue */ 
hsla(240, 100%, 50%, 1)       /* full opaque blue */ 

/* Whitespace syntax */
hsla(240 100% 50% / .05)      /*   5% opaque blue */ 

/* Percentage value for alpha */
hsla(240 100% 50% / 5%)       /*   5% opaque blue */ 

To summarize

Conflicting declarations will be applied in the following order, with later ones overriding earlier ones:

  1. Declarations in user agent style sheets (e.g. the browser’s default styles, used when no other styling is set).
  2. Normal declarations in user style sheets (custom styles set by a user).
  3. Normal declarations in author style sheets (these are the styles set by us, the web developers).
  4. Important declarations in author style sheets
  5. Important declarations in user style sheets

It makes sense for web developers’ stylesheets to override user stylesheets, so the design can be kept as intended, but sometimes users have good reasons to override web developer styles, as mentioned above — this can be achieved by using in their rules.

CSS Reference

CSS ReferenceCSS Browser SupportCSS SelectorsCSS FunctionsCSS Reference AuralCSS Web Safe FontsCSS AnimatableCSS UnitsCSS PX-EM ConverterCSS ColorsCSS Color ValuesCSS Default ValuesCSS Entities

CSS Properties

align-content align-items align-self all animation animation-delay animation-direction animation-duration animation-fill-mode animation-iteration-count animation-name animation-play-state animation-timing-function

backface-visibility background background-attachment background-blend-mode background-clip background-color background-image background-origin background-position background-repeat background-size border border-bottom border-bottom-color border-bottom-left-radius border-bottom-right-radius border-bottom-style border-bottom-width border-collapse border-color border-image border-image-outset border-image-repeat border-image-slice border-image-source border-image-width border-left border-left-color border-left-style border-left-width border-radius border-right border-right-color border-right-style border-right-width border-spacing border-style border-top border-top-color border-top-left-radius border-top-right-radius border-top-style border-top-width border-width bottom box-decoration-break box-shadow box-sizing break-after break-before break-inside

caption-side caret-color @charset clear clip clip-path color column-count column-fill column-gap column-rule column-rule-color column-rule-style column-rule-width column-span column-width columns content counter-increment counter-reset cursor

direction display empty-cells filter flex flex-basis flex-direction flex-flow flex-grow flex-shrink flex-wrap float font @font-face font-family font-feature-settings font-kerning font-size font-size-adjust font-stretch font-style font-variant font-variant-caps font-weight

grid grid-area grid-auto-columns grid-auto-flow grid-auto-rows grid-column grid-column-end grid-column-gap grid-column-start grid-gap grid-row grid-row-end grid-row-gap grid-row-start grid-template grid-template-areas grid-template-columns grid-template-rows

hanging-punctuation height hyphens @import isolation justify-content @keyframes left letter-spacing

line-height list-style list-style-image list-style-position list-style-type

margin margin-bottom margin-left margin-right margin-top max-height max-width @media min-height min-width mix-blend-mode

object-fit object-position opacity order outline outline-color outline-offset outline-style outline-width overflow overflow-x overflow-y

padding padding-bottom padding-left padding-right padding-top page-break-after page-break-before page-break-inside perspective perspective-origin pointer-events position quotes

resize right

scroll-behavior

tab-size table-layout text-align text-align-last text-decoration text-decoration-color text-decoration-line text-decoration-style text-indent text-justify text-overflow text-shadow text-transform top

transform transform-origin transform-style transition transition-delay transition-duration transition-property transition-timing-function

unicode-bidi user-select

vertical-align visibility

white-space width word-break word-spacing word-wrap writing-mode

z-index

Syntax

/* Keyword values */
color: currentcolor;

/* <named-color> values */
color: red;
color: orange;
color: tan;
color: rebeccapurple;

/* <hex-color> values */
color: #090;
color: #009900;
color: #090a;
color: #009900aa;

/* <rgb()> values */
color: rgb(34, 12, 64, 0.6);
color: rgba(34, 12, 64, 0.6);
color: rgb(34 12 64 / 0.6);
color: rgba(34 12 64 / 0.3);
color: rgb(34.0 12 64 / 60%);
color: rgba(34.6 12 64 / 30%);

/* <hsl()> values */
color: hsl(30, 100%, 50%, 0.6);
color: hsla(30, 100%, 50%, 0.6);
color: hsl(30 100% 50% / 0.6);
color: hsla(30 100% 50% / 0.6);
color: hsl(30.0 100% 50% / 60%);
color: hsla(30.2 100% 50% / 60%);

/* Global values */
color: inherit;
color: initial;
color: unset;

The property is specified as a single value.

Note that the value must be a uniform . It can’t be a , which is actually a type of .

Browser compatibility

The compatibility table on this page is generated from structured data. If you’d like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

Update compatibility data on GitHub

Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
Chrome Full support 1 Edge Full support 12 Firefox Full support 1 IE Full support 3 Opera Full support 3.5 Safari Full support 1 WebView Android Full support 1 Chrome Android Full support 18 Firefox Android Full support 4 Opera Android Full support 10.1 Safari iOS Full support 1 Samsung Internet Android Full support 1.0

Accessibility concerns

It is important to ensure that the contrast ratio between the color of the text and the background the text is placed over is high enough that people experiencing low vision conditions will be able to read the content of the page.

Color contrast ratio is determined by comparing the luminosity of the text and background color values. In order to meet current Web Content Accessibility Guidelines (WCAG), a ratio of 4.5:1 is required for text content and 3:1 for larger text such as headings. Large text is defined as 18.66px and bold or larger, or 24px or larger.

  • WebAIM: Color Contrast Checker
  • Understanding Success Criterion 1.4.3 | W3C Understanding WCAG 2.0

С этим читают