How to factor a color and boder-color into a single CSS style and apply it on other parts of the CSS styles
Tags: css,css3,asp.net-mvc-4
Problem :
I have the following styles in a Site.css which is part of a ASP.NET MVC4 Site
form label.error { font-size: 12px; color: #cc0000; }
form input:not([type="submit"]).error{ border-color: #cc0000; }
form select:not([type="submit"]).error{ border-color: #cc0000; }
.error { color: #cc0000; }
I want to know how can I modify that file to be able to change that #cc0000;
without changing it on every single line (factor out the color used for validation errors in this case)
Something similar to this:
errorStyle {
color: #cc0000 ;
border-color: #cc0000;
}
And then use it like this:
form label.error { font-size: 12px; errorStyle }
form input:not([type="submit"]).error{ errorStyle }
form select:not([type="submit"]).error{ errorStyle }
.error { errorStyle }
In this way if the client wants that color to be changed it easier to maintain.
Solution :
One simple way of avoiding repetition without using any pre-processors would be to apply the error
class (the one that contains the color
) to the form
element and then make use of currentColor
to use the same color that was applied to the parent.
The currentColor
is a keyword that points to existing color that is applied to the element. Support for this keyword is pretty decent and it works in all major browsers except IE8.
For border-color
, the default value is always the same as the color
applied to the element (which again is same as the currentColor
) and hence we could also use inherit
as the value instead of currentColor
. The inherit
basically tells the browser to inherit the parent's border color.
In the below snippet, I've applied currentColor
for one element and inherit
for another element to just show how both give same output.
form.error label {
font-size: 16px;
}
form.error input:not([type="submit"]) {
color: currentColor;
border-color: currentColor;
}
form.error select {
color: inherit;
border-color: inherit;
}
.error {
color: #cc0000;
}
<form class='error'>
<label>Hello</label>
<input type="text" />
<select>
<option>1</option>
</select>
</form>
If you want to apply the error
class to the individual elements also (that is, add red border and color only to the element with error) then that is also possible.
form.error label.error {
font-size: 16px;
}
form.error input:not([type="submit"]).error {
border-color: currentColor;
}
form.error select.error {
border-color: inherit;
}
.error {
color: #cc0000;
}
<form class='error'>
<label class='error'>Hello</label>
<input type='text' class='error' />
<select class='error'>
<option>1</option>
</select>
<input type='text' />
</form>