Css ampersand class name

Вложения в Sass

В Sass правила вложения CSS позволяют определить иерархию селекторов:

Это будет скомпилировано в следующее:

.title <> .title strong <> .title em <>

Поскольку strong и em появляются внутри правила .title (между двух фигурных скобок), то оба они будут начинаться с родительского селектора .title .

Цель вложения

Поскольку приоритет в CSS может оказаться непростым, то при написании селекторов обычно используют специфичность, путём комбинации нескольких классов или тегов, чтобы запретить взаимоисключающие правила CSS.

.description <> .description p <> .description p a <> .description p a:hover <> .description p strong <> .description table <> .description table tr <> .description table tr:nth-child(2n) <> .description table th, .description table td <> .description table td.empty, .description table th.empty <> .description table th <>

Чтобы предотвратить повторное написание .description давайте использовать вложения:

.description < p <>p a <> p a:hover <> p strong <> table <> table tr <> table tr:nth-child(2n) <> table th, table td <> table th <> table td.empty, table th.empty <> >

Вы можете пойти ещё дальше, заменив р и table для создания вложенных селекторов:

.description < p < a < &:hover <>> strong <> > table < tr < &:nth-child(2n) <>> th, td < &.empty <>> th <> > >

Помните про вложенность в HTML? Отступы в Sass позволяют воспроизвести, как элементы HTML вложены друг в друга.

Обратите внимание, что мы написали table и .empty только один раз в примере.

Будет генерироваться точно такой же CSS, с которого мы начали:

.description <> .description p <> .description p a <> .description p a:hover <> .description p strong <> .description table <> .description table tr <> .description table tr:nth-child(2n) <> .description table th, .description table td <> .description table td.empty, .description table th.empty <> .description table th <>

Амперсанд родительского селектора

Когда вы вкладываете селекторы в Sass, то это в основном добавляет пробел между родительским селектором и его ребёнком. Итак:

// SCSS .parent < .child <>> // превращается в CSS .parent .child <>

Пробел между .parent и .child определяет иерархию: этот селектор нацеливается на элементы HTML с class=»child» вложенные в class=»parent» .

Но что если вы хотите использовать псевдоселекторы, вроде :hover ? Или вам нужен селектор с добавленным классом? Вы можете использовать амперсанд, который является ярлыком для родительского селектора:

// SCSS .parent < &:hover <>&.other-class <> > // превращается в CSS .parent:hover <> .parent.other-class <>

Обратите внимание, что между .parent и :hover или .other-class нет пробела.

.parent.other-class будет нацелен на элементы HTML, которые содержат class=»parent other-class» .

Полный пример

.post-content <> .post-content a <> .post-content a:hover <> .post-content aside <> .post-content blockquote <> .post-content code <> .post-content h3 <> .post-content h3 a <> .post-content h4 <> .post-content h4:before <> .post-content h4:after <> .post-content p <> .post-content p:first-child <> .post-content p:last-child <> .post-content ul <> .post-content ul ul <> .post-content ul ul ul <> .post-content dl <> .post-content dl:before <> .post-content dl dt <> .post-content dl dd <> .post-content pre <> .post-content pre code <> .post-content table <> .post-content table tr <> .post-content table tr:nth-child(2n) <> .post-content table th, .post-content table td <> .post-content table th <> .post-content table td.empty, .post-content table th.empty <> .post-content table code <> .post-content table pre <> .post-content table pre:before <>
.post-content < a < &:hover <>> aside <> blockquote <> code <> h3 < a <>> h4 < &:before <>&:after <> > p < &:first-child <>&:last-child <> > ul < ul < ul <>> > dl < &:before <>dt <> dd <> > pre < code <>> table < tr < &:nth-child(2n) <>> th, td < &.empty <>> th <> code <> pre < &:before <>> > >

Источник

Читайте также:  Таблицы

Naming css classes

When writing css classes with kremling, you can choose however you would like to name your css classes.

Here are a few recommendations from the kremling team, but feel free to deviate in whatever way you’d like to:

Camel case vs hyphens

.myButton <> /* camel case */ .my-button <> /* hyphens */ 

You can use either camel case or hyphens when naming your css classes. Many css-in-js libs for React will encourage you to name css classes with camel case so that they are easier to use in javascript. However, with kremling it truly doesn’t matter since you will never need to reference your css classes with javascript variables.

Soft recommendation: Use hyphens, since that’s the de facto standard in html and css.

Start with very simple names

With kremling, you don’t have to worry about your css leaking out of its scope, which means you can name your css class something generic like .button <> and not have to worry about it colliding with dom elements in a completely different area of your app.

/* easy for humans to understand, so start by naming things like this */ .big-button <> /* might avoid some naming collisions, but only change to it if you need to */ .big-button-for-modal <> 

Ampersands (&)

If you are using kremling-loader, you’ll never have to insert ampersands into your css.

If you are not, you will have to add ampersands before every css rule.

Examples

/* if you're not using kremling-loader */ /* put an ampersand before your class name */ & .foo <> /* put an ampersand before any other type of css rule */ & div <> /* put an ampersand before each rule in a list of rules */ & .bar, & .baz, & .bing <> 

results matching » «

No results matching » «

Источник

Читайте также:  Find tag in xml java

The Sass Ampersand

The & is an extremely useful feature in Sass (and Less). It’s used when nesting. It can be a nice time-saver when you know how to use it, or a bit of a time-waster when you’re struggling and could have written the same code in regular CSS. Let’s see if we can really understand it.

You can nest as deep as you’d like, but it’s a good practice to keep it only a level or two to prevent overly specific selectors (which are less useful and harder to override).

The & comes in handy when you’re nesting and you want to create a more specific selector, like an element that has *both* of two classes, like this:

The & always refers to the parent selector when nesting. Think of the & as being removed and replaced with the parent selector. Like this:

The example with the & isn’t anything different than the example without the & . Nesting without the & is shorthand for nesting with it. We can think of the & as a mechanism that allows us to place the parent selector wherever we need it in our child selector. It allows us to nest with alterations. Let’s look at some more examples.

Using the & with pseudo classes

.button:visited < >.button:hover < >.button:active

The & in this case allows us to position .button directly next to pseudo classes without repetition in the authored code. If we left out the & from this example, basic nesting would put a space between them like this…

Using the & with the child combinator > , adjacent sibling combinator + , and the general sibling combinator ~ is a breeze. At first I thought you had to use the & , but:

// You don't actually have to do this. // Here, the ampersand is implied. .button < & >span < >& + span < >& ~ span < >>
// This compiles the same as above .button < >span < >+ span < >~ span < >>
.button > span < >.button + span < >.button ~ span

Qualifying based on context

Nested selectors don’t necessarily have to start with the ampersand. You can qualify a selector by putting the & on the right.

We’re repositioning the parent selector exactly where we need it. This is really useful for qualifying a selector based on a different parent. This will compile to:

Читайте также:  Php time 1 день

Tweaking the definition of the &

Think of the & as not only being replaced by the parent selector but as being replaced by the *compiled* parent selector. This is important when nesting more than two levels deep, where more than one level has an & . These next two wacky examples drive this point home.

Wacky but working example #1

For each & it will be replaced with the compiled parent selector. Therefore, every time there is an & we’ll insert .parent .child . Here’s the compiled CSS:

.parent .child div .parent .child .parent .child > a <>

Wacky but working example #2

To mentally-compile this CSS, start at the top-most layer and work your way down pealing off the outer layers and replacing the & with the new compiled parent selector. Here it is compiled:

.grand-child .parent .child.sibling <>

I found I was using the & for something it wasn’t from time to time. The & doesn’t allow you to selectively traverse up your nested selector tree to a certain place and only use a small portion of the compiled parent selector that you want to use. I’ve wanted to do something like this before:

.grand-parent < .parent < &(1) .child <>// Trying to get `.parent`, not `.grand-parent .parent` > >

It’s worth mentioning that @at-root allows you to break out of your nesting structure entirely to the “root” of your nesting tree.

This is nice. From an organizational perspective, all the code is still grouped together, which could be noted as an unsung benefit of nesting. @at-root can help keep specificity levels low because you no longer have the compiled parent selector to increase specificity. All the while still keeping your code conceptually organized with nesting:

Sometimes you need to beat-down the specificity of a 3rd-party CSS library to take ownership of the style:

It’s a lot less overpowering than using and ID, inline style, or !important and it could have benefits over qualifying the selector with an arbitrary parent element. The specificity level isn’t raised based on a selector’s context, but only by itself. With the & you can do that same thing like this.

Even though you can’t have two ampersands touching without the interpolation brackets — as we demoed earlier in our pseudo class example — you can have another selector touch the ampersand. Touching the ampersand works well with modifier classes.

This can be quite useful if employing a naming methodology (i.e. BEM) which uses dash and underscore combinated classes rather than combined selectors.

Источник

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