font

CSS Inheritance, The Cascade And Global Scope: Your New Old Worst Best Friends

Boost your skills online, with our friendly online workshops on front-end and design.

Using BEM, you’d be encouraged to place an explicit “element” class on each grid item:

But there’s no need. Only one identifier is required to instantiate the local scope. The items here are no more protected from outside influence than the ones in my version, targeted with > * — nor should they be. The only difference is the inflated markup.

So, now we’ve started incorporating classes, but only generically, as they were intended. We’re still not styling complex components independently. Instead, we’re solving system-wide problems in a reusable fashion. Naturally, you will need to document how these classes are used in your comments.

Utility classes like these take advantage of CSS’ global scope, the local scope, inheritance and the cascade simultaneously. The classes can be applied universally; they instantiate the local scope to affect just their child elements; they inherit styles not set here from the parent or global scope; and we’ve not overqualified using element or class selectors.

Here’s how our cascade looks now:

  1. global ( html ) styles and enforced inheritance,
  2. flow algorithm and exceptions (using the lobotomized owl selector),
  3. element and attribute styles,
  4. generic utility classes.

Of course, there may never be the need to write either of these example utilities. The point is that, if the need does emerge while working on one component, the solution should be made available to all components. Always be thinking in terms of the system.

Component-Specific Styles

We’ve been styling components, and ways to combine components, from the beginning, so it’s tempting to leave this section blank. But it’s worth stating that any components not created from other components (right down to individual HTML elements) are necessarily over-prescribed. They are to components what IDs are to selectors and risk becoming anachronistic to the system.

In fact, a good exercise is to identify complex components (“molecules,” “organisms”) by ID only and try not to use those IDs in your CSS. For example, you could place #login on your log-in form component. You shouldn’t have to use #login in your CSS with the element, attribute and flow algorithm styles in place, although you might find yourself making one or two generic utility classes that can be used in other form components.

If you do use #login , it can only affect that component. It’s a reminder that you’ve moved away from developing a design system and towards the interminable occupation of merely pushing pixels.

Читайте также:  Html разметки и верстки

Conclusion

When I tell folks that I don’t use methodologies such as BEM or tools such as CSS modules, many assume I’m writing CSS like this:

I don’t. A clear over-specification is present here, and one we should all be careful to avoid. It’s just that BEM (plus OOCSS, SMACSS, atomic CSS, etc.) are not the only ways to avoid convoluted, unmanageable CSS.

In an effort to defeat specificity woes, many methodologies defer almost exclusively to the class selector. The trouble is that this leads to a proliferation of classes: cryptic ciphers that bloat the markup and that — without careful attention to documentation — can confound developers new to the in-house naming system they constitute.

By using classes prolifically, you also maintain a styling system that is largely separate from your HTML system. This misappropriation of ‘separate concerns’ can lead to redundancy or, worse, can encourage inaccessibility: it’s possible to affect a visual style without affecting the accessible state along with it:

In place of the extensive writing and prescription of classes, I looked at some other methods:

  • leveraging inheritance to set a precedent for consistency;
  • making the most of element and attribute selectors to support transparent, standards-based composition;
  • applying a code- and labor-saving flow layout system;
  • incorporating a modest set of highly generic utility classes to solve common layout problems affecting multiple elements.

All of these were put in service of creating a design system that should make writing new interface components easier and less reliant on adding new CSS code as a project matures. And this is possible not thanks to strict naming and encapsulation, but thanks to a distinct lack of it.

Even if you’re not comfortable using the specific techniques I’ve recommended here, I hope this article has at least gotten you to rethink what components are. They’re not things you create in isolation. Sometimes, in the case of standard HTML elements, they’re not things you create at all. The more you compose components from components, the more accessible and visually consistent your interface will be, and with less CSS to achieve that end.

Читайте также:  Wordpress php do shortcode wordpress

There’s not much wrong with CSS. In fact, it’s remarkably good at letting you do a lot with a little. We’re just not taking advantage of that.

Источник

Font family inherit – CSS Inheritance | What is CSS Inherit Keyword? | List of CSS Properties that are Inherited

CSS Inheritance

Font family inherit: In CSS, inheritance manages what occurs when no value is named for a property on an element. This tutorial helps you more in learning about the CSS inherit Keyword along with the inherited and non-inherited properties. Click on the below available links and understand the concept of Inheritance in CSS.

CSS Inheritance

There are some CSS selectors that actually inherit styles from their parent element.

This helps us to specify the style of a particular element explicitly.

Some other properties make more sense to not be inherited.

For example, fonts, when we set the font-family to the body element, all other element inside the body tags get the same font. In better words, the children of the body elements inherit the CSS style/ font.

The background-color property, on the other hand, makes little sense to be inherited.

CSS properties can be classified into two types:

  • inherited properties, which by default are set to the computed value of the parent element
  • non-inherited properties, which by default are set to the initial value of the property

CSS inherit Keyword Definition & Syntax

In CSS, the inherit keyword defines that a property should inherit its value from its parent element. However, it can be used for any CSS property, and on any HTML element.

Syntax:

Example:

List of CSS Properties that are Inherited

List of the properties that inherit their parent style:

  • border-collapse
  • border-spacing
  • caption-side
  • color
  • cursor
  • direction
  • empty-cells
  • font-family
  • font-size
  • font-style
  • font-variant
  • font-weight
  • font-size-adjust
  • font-stretch
  • font
  • letter-spacing
  • line-height
  • list-style-image
  • list-style-position
  • list-style-type
  • list-style
  • orphans
  • quotes
  • tab-size
  • text-align
  • text-align-last
  • text-decoration-color
  • text-indent
  • text-justify
  • text-shadow
  • text-transform
  • visibility
  • white-space
  • widows
  • word-break
  • word-spacing

Forcing properties to inherit

Suppose one of the elements doesn’t inherit their parent, then we can explicitly state that to inherit their parent.

Читайте также:  Form fields in css

Forcing properties to NOT inherit

With contradiction, we also want some element not to inherit their parent.

We can use revert property value to explicitly tell not to inherit their parent.

This is very rarely used though.

Other special values

In addition to the keywords, inherit and revert , we can also set values like:

  • initial : use the default browser stylesheet if available. If not, and if the property inherits by default, inherit the value. Otherwise do nothing.
  • unset : if the property inherits by default, inherit. Otherwise do nothing.

Источник

font

Универсальное свойство, которое позволяет одновременно задать несколько характеристик шрифта и текста.

Синтаксис

font: [font-style||font-variant||font-weight] font-size [/line-height] font-family | inherit

Значения

В качестве обязательных значений свойства font указывается размер шрифта и его семейство. Остальные значения являются опциональными и задаются при желании. Для подробного ознакомления смотрите информацию о каждом свойстве отдельно.

inherit Наследует значение родителя.

Допускается в качестве значения использовать ключевые слова, определяющие шрифт различных элементов операционной системы пользователя.

caption Шрифт для текста элементов форм вроде кнопок. icon Шрифт для текста под иконками. menu Шрифт применяемый в меню. message-box Шрифт для диалоговых окон. small-caption Шрифт для подписей к небольшим элементам управления. status-bar Шрифт для строки состояния окон.

Примеры использования

Из типографики пошла запись указывать через слэш размер шрифта и межстрочное расстояние (интерлиньяж). Поэтому 12pt в данном случае означает размер основного текста в пунктах, а 10pt — интерлиньяж. В качестве семейства указывается рубленый шрифт ( sans-serif ).

Значение bold устанавливает жирное начертание текста, а italic — курсивное. В данном случае их порядок не важен, поэтому bold и italic можно поменять местами. Размер текста задается в процентах, а в качестве гарнитуры используется шрифт с засечками ( serif ).

Значение small-caps принадлежит свойству font-variant и устанавливает текст в виде капители (заглавные буквы уменьшенного размера). Значение normal применяется сразу к двум свойствам: font-style и font-weight .

HTML5 CSS2.1 IE Cr Op Sa Fx

     .layer1 < font: 12pt sans-serif; >h1 
Duis te feugifacilisi Duis autem dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit au gue duis dolore te feugat nulla facilisi.

Результат данного примера показан на рис. 1.

Применение свойства font

Рис. 1. Применение свойства font

Объектная модель

[window.]document.getElementById(» elementID «).style.font

Браузеры

Internet Explorer до версии 7.0 включительно не поддерживает значение inherit .

Источник

Оцените статью