Effectively reusing css rules within other rules - html

Here's a simple example of what I'm looking to do.
I want to define a css rule for a 2 gradient backgrounds - blueGradient and greenGradient.
I want all elements with css class foo to have the blueGradient rule, and on hover have the greenGradient rules.
So, here's how I want my HTML to look:
<div class="foo">Hello</div>
This should have a blue gradient normally, and green when I hover on it.
Ideally, I want my CSS to look like this (I know it's not legal):
.blueGradient {
...
}
.greenGradient {
...
}
.foo {
<#include blueGradient>
}
.foo:hover {
<#include greenGradient>
}
What's the best way to achieve this?
If something like this isn't possible, what's the best way to achieve this without having several copies of the blue/greenGradient definitions all over my CSS rules?
I know I can change my HTML to look like this:
<div class="foo blueGradient">Hello</div>
But then, how do I deal with the hover (I don't want to use JS)?

For rules that you want to apply to more than one selector, just separate them by commas:
.blueGradient, .foo {
/** blue gradient styling **/
}
.greenGradient, .foo:hover {
/** green gradient styling **/
}
In the same CSS file (and, indeed, in different files if you like) you can define styles for the same selector as many times as you like, so you can also define .foo and .foo:hover styling that will only be applied to these selectors, and will not shared with other .blueGradient and .greenGradient elements:
.foo {
/** foo-specific rules **/
}
.foo:hover {
/** foo:hover-specific rules **/
}
This does not require you to change your html. Where the same attribute is defined in both entries with different rules (e.g. margin: 0; and then later margin: 10px;) the last entry takes precedence.
If you also want the blueGradient styles to be applied to yet another selector .bar, just add it to the chain:
.blueGradient, .foo, .bar {
/** blue gradient styling **/
}
(Note in the example above, the .blueGradient and .greenGradient selectors are not required, unless they are being used elsewhere. You could replace them instead with a code comment that stated this was where the gradients were being applied if you wished.)

Using just CSS, the best way to accomplish this with minimal repetition of code is to do something like the following:
.blueGradient, .foo {
...
}
.greenGradient, .foo:hover {
...
}
Using a comma in your selector allows you to assign a block of CSS to multiple elements/IDs/classes at once.

You can't quite do what you're proposing in plain CSS. You might looking to using LessCSS. It has a feature called Mixins:
Mixins allow you to embed all the properties of a class into another class by simply including the class name as one of its properties. It’s just like variables, but for whole classes. Mixins can also behave like functions, and take arguments, as seen in the example bellow.
I know that's JS, but it wouldn't require you yo learn JS, just stick it on the page.
Otherwise you're stuck with what Justin Michael and others have said. Which is certainly good enough for most cases. Part of what you may need to do here is to train yourself to think in CSS rules.

Related

How to reuse css class content in another class without copying?

Is it possible to use existing css class as content in another class ?
I mean something like:
/* Contained in some library: */
.class1 { text-indent: 100 }
/* I can not change this: */
<span class="class2">
The definition for class2 is also contained in another library. So I can not change it directly.
/* But I want to do something like that in my CSS file: */
.class2 { .class1 }
I know it is not possible in that form. But maybe one can use some trick to achieve the behaviour without copying of the content of class1? I need this because I want to redefine class with content from another CSS class. Our project uses jQuery as well, but I would do it rather with CSS.
EDIT: I should explain more, I could not change how .class1 is defined, because this class is in a library, and I could not change mark up on span class.
It is imposible to do in standard CSS what you are commenting, as there is not pure inheritance.
Despite it doesn't apply with your code restrictions, this is the closer way to do it:
.class1, .class2 { text-indent: 100 }
.class2 {
/* Styles you want to have only in class 2 */
}
<span class="class2" />
On the other hand, as #A. Wolff has pointed out, you can still use js/jq to add class to specific elements: $(function(){$('.class2').addClass('class1')}); Then just set a specifc CSS rule for these elements.
In case you don't want to use JS, for something like that you'd need to use SASS or similar, which "compiles" to CSS.
CSS has no means to reference one rule-set from another.
Your options include:
Using multiple selectors for things with common rules
.menu,
.nav {
font-weight: bold;
}
.nav {
display: inline-block;
}
Using multiple classes on a single element
.menu {
font-weight: bold;
}
.nav {
display: inline-block;
}
<li class="menu nav">
Generating your CSS programatically
For example, with SASS
#mixin menu {
font-weight: bold;
}
.nav {
display: inline-block;
#include menu;
}
Yes, it is possoble.
Write:
.class1,.class2 {text-indent:100;}
.class1{color:red;}
.class2{font-size:30px;}
More info here.
Another option is to use LESS to do this. It's a very good tool and do some improvements to your CSS development.
Take a look at theirs documentation, it's very nice. About the compilers, I use Koala and recommend it.
You mentioned in one comment that you cannot use LESS, but I think perhaps you misunderstand how LESS (or another preprocessor) could help you. That is, you have not given any reason that I can see why you cannot use it (even in your update). As I understand your problem, you have the following parameters:
Cannot change html
Cannot change the css file that defines .class1.
You can change the css file that defines .class2.
If the above is correct, then here is how you use LESS (version 1.5+). You make your file defining .class2 a .less file. Then, to keep it clean, I believe you are going to have to do a two step process (it may be you can do step 2 without step 1).
Step One: Make the CSS into LESS
Create a file, let's say CSStoLESS.less and put this in it:
#import (less) /path/to/your/your-css-defining-class1.css;
This will import the css and make the processor consider it as LESS code. It is possible that the next step does that as well, I have not had opportunity to test it out.
Step Two: Use that file as reference in your LESS
By doing this in your .less file defining .class2:
#import (reference) /path/to/your/CSStoLESS.less;
.class2 { .class1; }
You are importing the previous css file that has been converted to less as reference only. This prevents you from getting duplicate selectors for .class1 or anything else contained in your original css file. Now you can use an inclusion of .class1 just like you show in your question to make the properties of .class1 become that of .class2.
It may be that this alone works:
#import (reference) /path/to/your/your-css-defining-class1.css;
.class2 { .class1; }
What I don't know is if the (reference) inclusion also defaults to making .css into LESS code like the (less) inclusion typecasting does in step one. I need to research this out more. If so, then it is a one-step, not a two-step process.
The best way would be to redeclare class1 just below your custom css ends and override it with the values that you are looking for. This way, the inherited values, that you cannot change + the values that you need to incorporate, both shall apply.
I am assuming you want whatever is in .class1 plus some extra properties in .class2
One way is to simply apply both classes to the element you want..
<span class="class1 class2" />
another is to name both classes when setting the properties
.class1, .class2 {text-indent: 100}
.class2{/*extra properties here*/}
You can define 2 classes in this way
.class1, .class2 { text-indent: 100 }
And it will work for you
Moreover if you want to ad some more in class2 then you can define it
.class2 { /*whatever you want here*/ }
Others mentioned SASS and LESS. Here's the solution of Stylus:
.class1
text-indent: 100
.class2
#extend .class1

!imporant equivalent for HTML class tag?

I'm dealing with a real hash of a site, so this is why I'm asking about this absurd question.
I've looked everywhere to find some sort of way to make a class override another class in the HTML class tag to no avail.
I can either do this, try to untie a ton of spaghetti (which I probably won't be allowed to do anyways), or something anyone else can recommend (would be greatly appreciated).
Is this possible?
class="myClass !important"
If not, is there some sort of equivalent?
Please help! Many thanks in advance!
No, that's not possible. You're going to have to iron out the CSS Specificity by yourself I'm afraid.
If you have the ability to change the HTML templates, you can always go in and add a <div id="override"> or something like that to the outer most wrapper of the page to use as the "master" rule in your CSS classes. Then, in the CSS, you can just add that ID before any of the existing classes or ones that you need to modify.
For instance, if you have the following and want to override the .some-class:
<div class="some-class">Bleh.</div>
And the corresponding CSS:
.some-class { color: red; }
You can wrap the whole thing with:
<div id="override">
<div class="some-class">Bleh.</div>
</div>
And add the #override (or whatever you want to name it) before the .some-class and this rule will take precedence over the other:
#override .some-class { color: green; } /* This will override the red color form the other rule */
.some-class { color: red; }
You can't use !important for entire selectors. You need to find the specific rules you want to override, and use !important on each.
You can add more than one class to a selector as follows:
class="myClass myClass2"
Above is what the class attribute would look like on your HTML element.
As far as the CSS goes, define the classes as follows:
.myClass {
color: black;
font-size: 14px;
}
The above is just a sample of some properties you may have.
Defining "myClass2" after "myClass" in your stylesheet will allow the properties from "myClass2" to overrided the matching ones in "myClass":
//This goes below myClass
.myClass2 {
font-size: 16px;
}
As long as "myClass2" is after "myClass", your font will take the size property of '16px;' The value of "myClass" will be overwritten by that of "myClass2". If "myClass2" comes before "myClass", you can use !important to ensure that style is taken over the one defined later:
//This goes above myClass
.myClass2 {
font-size: 16px !important;
}
Hope this helps.
CSS classes are just a group of styles so you can use class instead of inline style tag.
The !important keyword helps you to override a specific style and not working on classes.
So, for example:
Lets say that we have a css rule on every div somewhere in our CSS file
div{border:solid 1px #ff0000;}
And later on we have this rule:
div{background:#000000;}
Every div in our page will be with border and a background if we want to override the div css rules we need to do something like this:
div{background:none !important;border:none !important;/*...ADD YOUR CSS...*/}
you can create a css reset class to reset all the settings that you want and than add your css

inheriting from another css class

I have a problem here that i can't seem to figure out, till now my css has been a little slapdash and it was always a case of hack away till it looks right but i've decided to learn it properly and i'm trying to categorize things as much as i can.
So i have a layout that has an unordered list, this list has three li tags, within each of these li tags are two div each.
Now i have a class for each of these containers, they can be called container_1 container_2 and so on.
Now they have some unique attributes to each of them but they al also follow a set style for example, the divs in each li are side by side so its sets of two divs also they are all going to have round corners.
So i thought i could make a class class rounded_corners plus float_left and float_right so instead of re typing the code to round the corns or float something i could just reference thing class like this:
.container_1 .rounded_corners .float_left
{
}
.container_2 .rounded_corners .float_right
{
}
But when i use this i loose my styling so i used a comma and this allowed the sty;ing for the div to come back but the corners and floats didn't work.
So where am i going wrong with this?
This is my code, i have taken the code out that breaks the layout, but if you remove the comments you can see what happens.
http://jsfiddle.net/ragebunnykickass/g3Zaz/
The naming is a little different but you'll know what is meant.
Thanks.
CSS classes cannot inherit so what you have to do is split them to be as much atomic as possible. For example if you have a rounded-corners class and it may be applicable to containers:
.rounded-corners
{
/* Your CSS to define rounded corners */
}
Note that you define ONLY the properties for rounded corners. Now let's say you have a class to style containers (for example with a proper padding):
.container
{
/* Your CSS to define a nice container */
}
How to combine them together? This won't be done in CSS but in HTML, in this example this <div> inherits from both container and rounded-corners:
<div class="container rounded-corners">
</div>
Now suppose you need rounded corners for a non container object:
<div class="rounded-corners">
</div>
This is how CSS works. Do not compare them (because of name) with classes of object oriented languages. Each class define a set of attributes that will be applied to all elements that belong to that class. Final element style is the composition of the attributes inherited from each class that element belongs to.
NOTE: to summarize: answer is yes, you may have to repeat some code. You'll have trouble to manage your code (both HTML and CSS) if you use classes as short names for a style: you'll see you missed the point to separate content from style (because in HTML you'll define, using a class like rounded-corners, an explicit appearance). Imagine: next month you have to change your web-site style and fashion requirements impose you have square corners. You have to change your HTML code (unless you accept to have a rounded-corners class to apply a squared border). Much better if you simply say container and you let your CSS to define (and know) how a container should be rendered.
It may be applicable to you or not (it depends on your preferences, taste and development environment) but you may take a look to LESS. It's implemented as a JavaScript that will parse your CSSs. Of course you won't write a pure valid CSS but you'll gain many new features. In your case you may find mixins are what you need:
.rounded-corners
{
/* Your CSS here */
}
.float-left
{
/* Your CSS here */
}
.container
{
.rounder-corners
.float-left
}
You could have a CSS code like:
.container_1 {
}
.rounded_corners {
}
.float_left {
}
and then set a class to HTML element in this way:
<div class="container_1 rounded_corners float_left">...</div>
So the DIV element will inherit every style of every class!
Obviously, DIV it's just an example, you could use every tag!
If i get it well, you want a set of classes to apply to each div?
I'd break it up like that :
css
.rounded_corners {}
.float_left {}
.float_right {}
.container {}
and in the html
<li id="container_1" class="container float_left rounded_corners">...</li>
<li id="container_2" class="container float_right rounded_corners">...</li>
etc...

I want to apply an existing CSS style to all labels on a page. How?

Note, this is different than the older question How can I apply CSS on all buttons which are present in that page? because this is an already existing style. So given that a style, which we'll call "standard_label_style" already exists in an included CSS file, what can I do to say that all the labels on this page should have that style short of adding:
class="standard_label_style"
to each and every one? And yes, I know I could apply the styles ex-post-facto with a snippet of jQuery or JavaScript code. I'm just trying to learn how I'm supposed to do it with CSS.
Follow Up
I've gotten several comments that say just use syntax like this .standard_label_style, label... Unfortunately that does nothing like what I want. That would allow me to apply additional rules to the standard_label_style class, as well as rules to labels within this page, but would not allow me to apply that style to all the labels on this page. To see an example of this, here is a stylesheet and html to demonstrate. The label without a class will still not appear in red but that's what I'm hoping to have happen. I want to apply an existing class to all those labels on the page, not just the one with the class and without adding new styling on this page, the existing style should be the only style.
included.css:
.standard_label_style { color: red; }
test.html:
<html>
<head>
<link rel="stylesheet" type="text/css" href="included.css">
<style>
.standard_label_style, label { }
</style>
</head>
<body>
<label class="standard_label_style">Test Label</label><br/>
<label>Unclassed Test Label</label>
</body>
</html>
CSS doesn't really work like that.
You can apply a style to all labels directly:
label {
color: Lime;
}
or apply a class to all labels
.labelClass {
color: Lime;
}
<label class="labelClass"></label>
You can also have multiple selectors, so you could ammend your current style to be
.labelClass, label {
color: Lime;
}
What you can't do in standard CSS is something like
label {
.labelClass;
}
The good news is that there are a bunch of server side libraries which make CSS suck less and let you do exactly this kind of thing, see for example dotLess if you're using .NET which provides nested rules and a basic inheratance model.
To apply a style to every label on the page, use this CSS:
label {
/* styles... */
}
If you have an existing style (e.g. "standard_label_style") in the CSS already, you can apply that to every label:
.standard_label_style, label {
/* styles... */
}
This will affect every label through the site, so use with caution!
In your css file, can't you just put
.standard_label_style, label
{
//styles
}
.standard_label_style, label {
/* stuff */
}
I'm not sure you can... one possible workaround (feels a bit hackish though) is to attach the style to your body tag, then change the css to be this:
body.standard_label_style label{
//Your styles here
}
One of the most underused CSS tricks of all time: Give your bodies an id or class!
HTML:
<body id="standard_label_style">
<label>Hey!</label>
</body>
CSS:
#standard_label_style label{
the styles
}
will take the styles, while
HTML:
<body id="custom_label_style">
<label>Custom!</label>
</body>
Will not.
You are dealing here with CSS precedence. Declarations which are "more vague" (body tag, classes) are applied before declarations which are "less vague" (specific elements, inline CSS).
Thus your answer depends on how the stylesheet is defining label styles. If for example it says label {...}, then that's fairly specific, and your best bet is to use a more specific CSS style, see:
http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/ (good tutorial?)
CSS precedence
The level of "specificity" you need to override, as I said, depend on how specific your other stylesheet was. According to the link, "CSS embedded in the html always come after external stylesheets regardless of the order in the html".
There is also a chance that if you yourself define label {your custom css} that should work, if you import your stylesheet afterwards. It is what I would try first to see if it works. Have you tried this? What was the result?
Note that if you want to completely override the other stylesheet, you will need to also reset any CSS you are not using by settings its values to inherit or as appropriate.

CSS: reset styles defined in an untouchable stylesheet

I need a simple <hr/> in a page that extends a default one (I'm using Django template framework); in this default page, a standard and untouchable stylesheet styles HR with border:none; height:1px but I would like to reset these styles to their default values.
I tried putting {border:1px inset; height:auto;} in my page but I didn't get the same aspect as having no style at all.
Is there a method to restore the default style for a tag?
In order to make your rule apply, you'll need to ensure that you give your rule a greater specificity than the existing rule in order to override it.
For example, if the rule is this:
hr {
/* rules */
}
Then you would need to do something like this:
html hr {
/* your rules */
}
Scores are calculated by these basic rules:
elements, like div are worth one point
classes, like .comment are worth 10 points
ids, like #user123 are worth 100 points
The total score for the selector is the sum of all of its parts, so div.class is worth 11 (10 for the .class and 1 for div
(It's actually a bit more complicated than this - see this article for details - but this explanation works as a general rule)
Edit:
I just saw your comment about not knowing the defaults.
According to Firebug, an hr appears to look like this:
hr {
height: 0;
width: 100%;
border: 1px solid #808080;
margin: 8px 0;
}
You can use the tools provided in other browsers to see if they use a different set of styles, then decide for yourself which ones would be the best ones to use.
Try YUI 2 Base CSS, seems to be doing what you want. Or even YUI 3 Base CSS
There is a possibility to "restore" default styles only for a certain context
Update
Just checked - Base CSS does not include styles for hr element
The default stylesheet for HTML documents, without any overrides, is defined by the W3C. You can find the full default stylesheet here: http://www.w3.org/TR/CSS2/sample.html
Alternatively, you could use Firebug in Firefox (or any similar tool) to view the styles of an <hr /> element on a test page without any styles applied.
Sure, you need to give your styles a bigger weight; add an id to your < hr/>, or do this in CSS:
html body hr { ... your styles ... }
No. You either have to not apply the styles in the first place, or override every broken style with explicit values.
You can also give your styles more weight with the !important property. If the original is like this:
.someClass { color: red }
You can override it with this:
.someClass { color: green !important}