santa
santa

Reputation: 12512

New class to use other class attributes

I am wondering if it is possible to use @extend to utilize properties of one class in another. For example, if I have two CSS files that load on the same page in the following order:

<link rel="stylesheet" href="/css/one.css" media="screen">
<link rel="stylesheet" href="/css/two.css" media="screen">

where one.css has class:

.foo {
  color: red;
}

Can I do something like that in two.css:

.bar {
  @extend .foo;
}

Upvotes: 0

Views: 47

Answers (2)

Bumhan Yu
Bumhan Yu

Reputation: 2297

It'll require a pre- or post-processor to achieve such things, or a CSS-in-JS solution.

You could consider:

  1. a BEM-like approach to cascade what's common and override what's unique.
.foo {
  color: black;
  background: yellow;
}

.bar {
  color: red;
}

.baz {
  color: blue;
}
<span class="foo">This is FOO</span>
<span class="foo bar">This is FOO + BAR</span>
<span class="foo baz">This is FOO + BAZ</span>

... or

  1. a CSS Custom Properties (a.k.a CSS Variables) to apply and override more flexibly.
:root {
  --main-color: black;
}

.foo {
  color: var(--main-color);
}

.bar {
  --main-color: red;
}
<span class="foo">This is FOO</span>
<span class="foo bar">This is FOO + BAR</span>

Upvotes: 1

Cichy
Cichy

Reputation: 109

Right now pure CSS don't have any mechanism like this, I know there is a way in Sass to do this with @extend. For some cases it's enough to use comma separated selectors for example:

.foo,.bar{
  font-size:40px;
}
.bar{
  color:red;
}

in this example You are doing common part for .foo and .bar selectors and add color:red only for .bar

Upvotes: 1

Related Questions