user746461
user746461

Reputation:

Define new CSS color name

We know the HTML standard defines a bunch of colors, but can I define and use new color in less css?

Say I want to have a color DoctorWhite, and I want to use it like

background-color:DoctorWhite;

I know less css can define variables and use it with the at(@) notation. But it doesn't look like a native color.

Is it achivable in less css? Or does any other CSS pre-processor support this?

Upvotes: 1

Views: 6530

Answers (2)

henry
henry

Reputation: 4385

No.

In LESS, like you said, variables are marked with an @. In Sass, they are marked with a $. Examples if your DoctorWhite was #fffffe:

LESS: @DoctorWhite: #fffffe; div {background-color: @DoctorWhite}
Sass: $DoctorWhite: #fffffe; div {background-color: $DoctorWhite}

As @blonfu says, in Stylus they aren't marked with anything - so if your objective is to make anyone who sees your pre-preprocessored stylesheets think your custom color name is a standardized color name, that might work. (But it's hard to imagine the use case…)

Stylus:

DoctorWhite = #fffffe

put a bunch of other styles here so the viewer doesn't notice you defined DoctorWhite

div
  background-color DoctorWhite

But in all cases, you aren't actually defining a new color name in the sense that HTML has a color WhiteSmoke. The compiled CSS (as it appears in the loaded stylesheet, and as it will appear in a browser's inspector) will still use the hex value you gave DoctorWhite — in all of the above examples, or if you do a custom CSS property solution, the CSS will be
div {background-color: #fffffe}.

Upvotes: 0

trashr0x
trashr0x

Reputation: 6565

Have you considered using CSS custom properties?

:root {
  --stackoverflow: #f69c55;
}
.rectangle {
  width: 100px;
  height: 100px;
  margin: 10px auto;
}
.rectangle.default-color {
  background-color: black;
}
.rectangle.custom-color {
  background-color: var(--stackoverflow);
}
<div class="rectangle default-color">
  <!-- will become black -->
</div>
<div class="rectangle custom-color">
  <!-- will become orange -->
</div>

Here, the var() function is used to set the value of the background-color property of .rectangle.custom-color to the value of the --stackoverflow variable (i.e. #f69c55).

Bear in mind that this is a W3C Candidate Recommendation (intended to become a W3C spec), so as @Ricky_Ruiz suggested, make sure it is supported by the browsers you are targeting using a service like CanIUse.

Side note: The two dashes (--) at the beginning of the custom variable name are not arbitrary:

A custom property is any property whose name starts with two dashes (U+002D HYPHEN-MINUS), like --foo. The production corresponds to this: it’s defined as any valid identifier that starts with two dashes.

Have a look at section 2 of the Candidate Recommendation document for more.

Upvotes: 5

Related Questions