1

Can I call a rule in the statement of another rule if CSS?. Something like this:

.myFirstRule
{
    color: white;
}

.mySecondRule
{
    width: 1000px;
    myFirstRule;
}

Thank you.

Sorry about my english

2
  • 3
    In CSS, no. However, you can apply styles to more than one selector, such as: .myFirstRule, .mySecondRule {color: white;} Make sure you separate the two selectors with a comma. Commented May 22, 2015 at 14:09
  • 1
    @DanOrlovsky - This should be an answer, not a comment Commented May 22, 2015 at 14:10

4 Answers 4

4

In CSS, no you cannot. You can, however, apply styles to more than one selector at a time, such as:

.myFirstRule, .mySecondRule { color: white; }

Make sure each selector is separated with a comma, and you're good to go.

Sign up to request clarification or add additional context in comments.

2 Comments

The second Rule is called from another file
That doesn't matter. Just because a selector exists in one CSS file does not mean it cannot exist in the other.
2

You can't do this in plain CSS but there are two solutions to your problem:

One: Use multiple selectors

<div class="myFirstRule mySecondRule"></div>

Two: Use SASS (or LESS, I suppose)

.myFirstRule {
  color: white;
}
.mySecondRule {
  width: 1000px;
  .myFirstRule;
}

Alternatively, still with SASS, you could also do this with a mixin:

// Define here
@mixin reusableRule {
  color: white;
}

.myFirstRule {
  @include reusableRule;
}
.mySecondRule {
  width: 1000px;
  @include reusableRule;
}

Comments

1

No, you can't do that in pure CSS.. You can use a comma or , to apply a property to multiple selectors

Try this:

.myFirstRule, .mySecondRule {
    color:white;
}

.mySecondRule
{
    width: 1000px;
}

1 Comment

The second Rule is called from another file
1

This is not possible with normal CSS, but you could try using SASS or LESS instead, which both compile to CSS. They allow this behavior through "mixins".

For example in LESS you could do:

.myFirstRule
{
    color: white;
}

.mySecondRule
{
    width: 1000px;
    .myFirstRule;
}

which would generate CSS:

.myFirstRule
{
    color: white;
}

.mySecondRule
{
    width: 1000px;
    color: white;
}

2 Comments

The second Rule is called from another file
LESS and SASS both merge multiple files into a single .CSS file for deployment, so separating the rules into files based on their responsibility is ideal. So yes, LESS and SASS would both allow you to include one rule into another when they are in separate files.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.