<td class="blue">
Hi1
Hi2
Hi3
<div>Not Blue</div>
</td>
I want the class in the tag ("blue") to make Hi1,Hi2 and Hi3 blue.
So what should be the head of that class?
????
{
color:blue;
}
Using a descendant selector:
td.blue a {
color: blue;
}
Or if you only want it for immediate children, a child selector:
td.blue > a {
color: blue;
}
Reference material:
Selectors supported by most browsers: CSS 2.1
Newer selectors supported by some browsers and by various JavaScript libraries (for interacting with the DOM): CSS3 Selectors
Use the following. This means all a elements within any td element that has a class name of blue should be displayed in blue.
td.blue a {
color:blue;
}
However, you should note that semantically it is unwise to give your CSS classes style-specific names (like 'blue' or 'bold' or 'center') - if later you decided to change the colour to red, you would have to change all references to the blue class to red (potentially lots of work) or instead be left with really confusing class names that don't make sense.
Try naming the class after what the elements in question mean. So in this case, it might be td.links for example.
The CSS selector you need would reference both the blue class and the a tags beneath it.
.blue a {
color:blue;
}
Note that there is another syntax which you may also want to consider:
.blue>a {
color:blue;
}
note the > between .blue and a in this example. Both examples will work for your given HTML code, but this version more specific than the first, because it only affects <a> tags that are immediate children of blue. In other words, if you had an <a> tag inside the <div>, the first version would affect it, whereas this version wouldn't.
The downside is that IE6 doesn't support the > selector, so if you need to support IE6 users, you must use the first version. Fortunately, IE6 users are becoming fewer, but there are still a few of them out there.
One other thing: I'd also advise you to avoid using class names which refer to the actual colour. It's usually better to call it menulink, or something like that.
The reason for this? Imagine in the future you want to change your site a bit, freshen it up for a new version. Maybe new corporate colours afer a rebranding exersise. Whatever. You could do that without an change at all to your HTML code; just a CSS update:
.blue a {
color:red;
}
...but now your CSS doesn't make sense. If you'd called it menulink, you will always know what that class refers to, even if things change over time.
Try this.
td.blue a {
color: #0000FF;
}
This sets all a tags that are within a td tag with a class of blue.
Related
I'm reading the book: CSS Mastery: Advanced Web Standards Solutions, and finding the css code inside is almost writed in this format:
elementName#idName
elementName.className
but, I'm used to write code ignoring element name with this format:
#idName
.className
so, I want to figure out what difference is between the two format.
Actually, I understand when should use type.class. And, I just want to find out the impact when I use type.class insead of only using .class when there is only one kind of tag here.
There must be some impact on performance.
Here's a real life scenario as when to use elementName and when to just use class or id name:
HTML:
<a class="blue">I'm blue and underline</a>
<span class"blue">I'm blue and bold</a>
CSS:
.blue {
color:blue //will make both <a> and <span> blue
}
a.blue {
text-decoration:underline // will make only the <a> tags underline
}
span.blue {
font-weight:bold //will make only the <span> tags bold
}
but remember when it comes to IDs you should not have duplicate IDs on your page anyway, this is more practical for classes
The difference between the two is that the first:
element.class
Is calling the element with that specific class.
And the second:
.class
Is calling all elements that contain this class
I think that the element inclusion in the selector is a holdover from days where some browsers required it (I think IE5 does, but I could be wrong). This is no longer necessary, and it does not make sense to include element selector for at least three reasons:
It slows the selector down since the element selector is slower than the other two -- especially id. Assuming selection is optimized so that fast selection is done first (e.g. the element with the matching id is found before the element selector is checked), there is still the additional step of checking the element selector.
It's not as extensible since you can't change the element without also having to change the selector. The implication is also that div.class would function differently than label.class, but I think that the class should be descriptive enough.
It changes the specificity of the selector. This could be very frustrating for some developers who may want to change <div class="foo"> from green to red:
div.foo { color: green; }
/* below is not applied since the above has higher specificity */
.foo { color: red; }
I've never heard an argument that supports type.class unless old browsers need to be supported.
in my html I have
<div id="mainNewsBody" class="news">
<a class="readMore" href="/News/Details/1">read more ...</a>
</div>
I tried to style read more ... snipper with this css
#mainNewsBody .news .readMore a{
color: #7F0609;
}
to actually apply this style I have to use !important keyword in color property.
I know that this !important keyword force to use that property but I do not understand why that is the case here, because I explicitly told to match on particular id with particular class element and inside that element to mach link.
Can someone englight me.
Thanks
Try this one:
.news .readMore {
color: #7F0609;
}
There's no need to call for id and class name for the same element.
It's a.readMore instead of .readMore a (the first case would search for an element with class .readMore and append the CSS to any children a-elements)
and #mainNewsBody .news should be #mainNewsBody.news (you should 'concatenate' the id and class since they refer to the same element)
making a total of #mainNewsBody.news a.readMore
Fiddle
EDIT
I see many notes on simplifying your css to just classes. This really depends on what you're trying to accomplish. If you're working with a huge CSS file, I'd recommend specifying as strict as possible. This to prevent any CSS being applied on places where you don't want it to.
a { } for example will mess with all your links, a.news { } will only mess with a class='news'
It'd the specificity which is troubling you, the more elements class id you have in your selector, more specific your selector is.
So for example
.class a {
}
is more specific than just
a {
}
Just see to it that you do not have a more specific selector, if you've than you need to make the current one more specific or use !important declaration as you stated.
In the above snippet this is incorrect
#mainNewsBody .news .readMore a
It will search for an element having class news inside an element having an id mainNewsBody which is not true in your case so either use this
#mainNewsBody a.readMore {
/* This will be more specific than the below one
as you are using id here and not class */
color: #7F0609;
}
Or use
.news a.readMore {
color: #7F0609;
}
Ozan is right, remove the "mainNewsBody" ID from the CSS if it's not absolutely necessary.
.news .readMore a{
color: #7F0609;}
If you want to be really specific and need to include the ID in the CSS selector remove the space from in-front of ".news"
#mainNewsBody.news .readMore a{
color: #7F0609;}
CSS Tricks - Multiple Class ID Selectors
CSS rules marked !important take precedence over later rules. !important ensures that this rule has precedence.
Probably your code is generating inline css for the a element, or you have another less specific definition for a element with !important keyword somewhere else.
Inline styles have priority higher than styles defined outside the element. To overcome the inline style or a style with !important keyword by a less specific definition, you need to define it by the keyword !important and a more specific definition.
I'm trying to be more modular in my CSS style sheets and was wondering if there is some feature like an include or apply that allows the author to apply a set of styles dynamically.
Since I am having a hard time wording the question, perhaps an example will make more sense.
Let's say, for example, I have the following CSS:
.red {color:#e00b0b}
#footer a {font-size:0.8em}
h2 {font-size:1.4em; font-weight:bold;}
In my page, let's say that I want both the footer links and h2 elements to use the special red color (there may be other locations I would like to use it as well). Ideally, I would like to do something like the following:
.red {color:#e00b0b}
#footer a {font-size:0.8em; apply-class:".red";}
h2 {font-size:1.4em; font-weight:bold; apply-class:".red";}
To me, this feels "modular" in a way because I can make modifications to the .red class without having to worry so much about where it is used, and other locations can use the styles in that class without worrying about, specifically, what they are.
I understand that I have the following options and have included why, in my fairly inexperienced opinion, they are less-than-perfect:
Add the color property to every element I want to be that color. Not ideal because, if I change the color, I have to update every rule to match the new color.
Add the red class to every element I want to be red. Not ideal because it means that my HTML is dictating presentation.
Create an additional rule that selects every element I want to be red and apply the color property to that. Not ideal because it is harder to find all of the rules that style a specific element, making maintenance more of a challenge
Maybe I'm just being an ass and the following options are the only options and I should stick with them. I'm wondering, however, if the "ideal" (well, my ideal) method exists and, if so, what is the proper syntax?
If it doesn't exist, option 3 above seems like my best bet. However, I would like to get confirmation.
First of all you cannot do apply-class:".red";
to perform this type of action i will suggest you to use this method
.red {color:#e00b0b;}
h2 {font-size:1.4em; font-weight:bold;}
.mymargin{margin:5px;}
<h2 class="red mymargin">This is h2</h2>
and to use in div
<div id="div1" class="red mymargin"></div>
In this case if you will change in .red class.it will be changed everywhere
Short answer: There's no way to do this in pure CSS.
Longer answer: Sass solves this problem via the #extend directive.
.error {
border: 1px #f00;
background-color: #fdd;
}
.seriousError {
#extend .error;
border-width: 3px;
}
This lets you keep your CSS modular in development, though it does require a precompilation step before you use it. It works very nicely though.
You can use the DOM in javascript to edit the id and/or class attributes of HTML tags dynamically.
I agree with DarthCaesar and jhonraymos. To update a class using JavaScript, all you would need is a simple:
function toggleColorClass(e){
var redClass = document.getElementsByClassName('red');
redClass.removeAttribute('class', 'red');
/*Set the class to some other color class*/
redClass.setAttribute('class', 'blue');
}
Of course, to make this work, you would need to include the above function in your document somewhere... if this is all the JS you're using you can probably stick it in the head or even use it inline. You would probably also want to write it so that the toggle goes in both directions, i.e. turning red on and off. Furthermore, jhonray's snippet is probably how you would want to mark up your CSS.
Our production environment is using an adaptation technology that is incompatible with multiple css classes. This means it's easy to forget and use two classes when styling HTML, and have it break once it gets to production.
I would like to use CSS as a way to highlight when someone forgets and accidentally applies two classes to an element.
Something like this is my intent, although of course this is invalid. It should highlight any element that has two classes applied to it:
.*.* { /* not valid (I wish) */
outline:2px dotted red;
}
I understand that this would work if I knew the classes, the problem is I want to flag ANY two classes:
.classA.classB { /* not good enough */
outline:2px dotted red;
}
I understand I could do this with JS and a bookmarklet, and maybe that is the only solution. If it is possible with just CSS that would be better as it would automatically flag things for all developers and QA.
I just found an acceptable answer:
[class*=" "] {
outline:2px dotted red;
}
This highlights anything with a space in the class attribute. It gets some false positives, because sometimes spaces in a class attribute happen legitimately as a result of legible server side code, but I prefer the false positives to false negatives.
Any better ideas?
To remove most false positives (e.g. space-padded attribute values), you can use this selector:
[class*=" "]:not([class^=" "]):not([class$=" "]) {
outline: 2px dotted red;
}
This still does not filter out repeated classes in values such as class="foo foo" as pointed out by Phrogz in your own answer, but it's better than nothing, and I think that's much less likely to occur than class attributes with whitespace padding.
This is not possible using CSS alone.
And, if I may say so, your production environment is silly. CSS without multiple classes is like a tag cloud with only one tag allowed per item. It defeats some of the purpose. Fix your production environment to not abuse CSS in this manner, instead of limiting your authors from properly, semantically describing the content.
In designing the HTML and CSS for a page, when should I use
img.className
versus
.className
versus
#idName
or some other variant?
Are there guidelines or recommendations?
Summary from answers
Thank you to all answerers - there is some excellent stuff here!
make CSS as specific as possible
use an OO approach
order: #id, tag, tag.className, .className
when to use each selector, also class/ID comparison
give selectors names based on purpose, not what they look like
use advanced selectors for smaller code, leave CSS classes for exceptions/overrides only
manage ASP.NET munging ID
In general you should be as specific as the item demands.
There is no general rule, it depends on the style in question.
A lot of people will recommend you keep to the lowest specificity with the theory that this allows the maximum cascading reuse but this is absolutely toxic in real world situations where you have multiple developers all working on slightly different versions of what a .foo might look like. Pollution from inheritance you did not want leads to massive bloat in trying to undo that locally or time-loss in refactoring.
The best guideline I always offer is to try and think of CSS in OO terms: class selectors map to interfaces more or less, tags map to classes, and ID selectors map to instances. Consequently decide if the style you want to apply really applies to that thing, all things like it, or anything which wants it.
I also strongly encourage you to make use of high level IDs on wrapper elements so you can write selectors in a namespace like fashion (i.e. #foo .bar, #foo .baz where #foo is unique to a page or set of page designs) which allows you both a level of specificity which reduces cross-design pollution and a level of generality which lets you make the most of cascading CSS reuse.
Best of both worlds.
It depends on the intended semantics, and, as others said, be as specific as possible.
#idName for unique elements on the page. Good examples are #header and #footer
TAGNAME for general purpose page styling.
TAG.classname and .classname for exceptions/overrides to the above rules.
And don't forget the use of advanced selectors. A bad example:
<style>
H1{ font-size: 200%; color: #008; }
#mainMenu { color: #800; }
.in_the_menu { color: #800; font-size: 150%; }
</style>
<h1>Hello World!</h1>
<div id="mainMenu">
<h1 class="in_the_menu">My Menu</h1>
</div>
The same could have been achieved with:
<style>
H1{ font-size: 200%; color: #008; }
#mainMenu { color: #800; }
#mainMenu H1 { color: #800; font-size: 150%; }
</style>
<h1>Hello World!</h1>
<div id="mainMenu">
<h1>My Menu</h1>
</div>
The second example gets rid of the superflous "class" attribute on the H1 element in the "mainMenu" div. This has two important benefits:
The HTML code is smaller and cleaner
You are less likely to forget to add the class attribute
If you take good care of you CSS, and make use of proper advanced selectors, you can nearly completely leave out CSS classes. And keep them only for exceptions/overrides.
Take this example which draws boxes with headers:
#content H2{
border: 1px solid #008789;
padding: 0em 1em;
margin: 0.2em 0em;
margin-bottom: 1em;
font-size: 100%;
background: #cccb79
}
#content H2 + DIV{
margin-top: -1em;
border-left: 1px solid #008789;
border-right: 1px solid #008789;
border-bottom: 1px solid #008789;
margin-bottom: 1em;
}
Now, as soon as you follow a H2 with a DIV in the #content element, you have a nice box. other DIVs and H2s are left alone:
<div id="content">
<h2>Hello Box!</h2>
<div>Some text</div>
<div>Some more text</div>
<div>Some more text</div>
<h2>And another title</h2>
</div>
If you get these rules right, you hardly ever need classes, and can work with IDs and TAG names alone. And as an added bonus, your HTML will be a lot nicer to read and maintain.
You preference should be, in order from highest to lowest:
id
tag
tag.className
.className
ID selectors are fast. Tag selectors are reasonably fast. Pure class selectors are slow because the browser essentially has to interrogate every element and see if each has that class. Getting elements by ID or tag name are "native" operations from a browser's context.
Also, I find it good practice to make your CSS selectors as restrictive as possible otherwise it just turns into a mess and you end up getting all sorts of unintended consequences where CSS rules apply where you didn't otherwise expect, which often forces you to create a similar yet different selector just so none of the rules regarding the first don't apply (translating into more mess).
Basically if you know if you only use a class on div elements then do this
div.className
not
.className
If you apply a class to several elements just list them:
h1.selected, h2.selected, h3.selected
instead of
.selected
In practice I find very few situations where you need to use "naked" class selectors or where it is advisable to do so.
you should use the selector best describing your rules
id: when you want to select one single element
.classname: when you want to style elements regardless of their tag
tag.classname: when you want to style only tags with the given class
tag tag tag: when you want to style all subelements of a tag
Class selectors
.className
This is to be used when you have more than one element on the page that you would like to apply the same style to. It can be to any tag element. So in the following all will use the same style as set out by the .className.
<p class="className"></p>
<img src="/path/to/image.png" class="className" />
But you can also restrict it like so:
img.className
By placing the tag along with the style definition, you're saying that this style is only to be used when it's the class used by that particular tag, in this case, an image.
HTML code will look like this:
<img src="/path/to/image.png" class="className" />
If you have other elements on the page using the same class style, but are not of the same tag, then the styles set out in this will not be applied and they will take on the more generic version as mentioned in the first example.
So repeating the example above:
<p class="className"></p>
<img src="/path/to/image.png" class="className" />
Only the image will take on the style as set out by img.className whereas all the rest will take on the style rules set in .className.
ID selectors
#idName
This is to be used when there is only one instance of a particular element that you wish to apply the style to.
You can also force it to apply only in certain tag conditions as you have earlier with the class definitions.
p#idName
This example will only apply to the paragraph block marked with the ID:
<p id="idName">
If you were to put that id on another element, like this:
<div id="idName"></div>
Then it will not take on the style set out and be ignored.
As to your two first selectors, the first of the two will overwrite the second, as it's more specific. You can calculate the specificity of a selector.
One thing worth noting is that some server side scripting technologies (most notably ASP.NET) don't play well with using IDs for your styling. If there is a chance your design will be used with such a technology, I recommend forgetting about #id selectors and use tag.className instead.
The reason is that ASP.NET actually changes the ID that ends up in the HTML based on a number of criteria, if the tag is output by a server side control.
I know this is a pretty old question but for all those who are reading this just now...
There are 4 categories of rules in general:
ID Rules, Class Rules, Tag Rules, Universal Rules.
And it's important to mention that class selectors are faster than tag selectors. So you should always use them in the following order
1. ID Selector
2. Class Selector
3. Tag Selector
4. Universal Selectors
In your case you should never use the tag name before class name.
You can find more information here: Writing efficient CSS
It really depends on the situation:
.error{
color:red;
}
p.error{
background-color:yellow;
}
div.error{
background-color:grey;
}
Always use the cascading effect of CSS to your advantage.
It's good practise to use the least specific rules you can for each rule.
How you structure your CSS will depend on the particular needs of the design.
Yes. You may want to use the same classname for two elements in the future. Be explicit and clear. This will also prevent class-rules from overlapping onto unintended elements.
h1.title { font-size:18px; } /* My h1's are big */
p.title { font-size:16px; } /* My p's are smaller */
.title { color:#336699; } /* All titles are blue */
Use ID's only when necessary, and only once per page.
When to use what depends on what you want to select. img.className (type selector + class selector) selects only IMG elements that’s in the class “className” while .className (just class selector) selects any element that’s in that class and #idName (id selector) any element with the ID “idName”.
But besides that, the selector all have a differente specificity that affects the order in which the properties of that rules overwrite the one of others.
So if you have an IMG element with the ID “idName” that’s in the class “className”:
<img src="…" id="idName" class="className">
The properties of the rules would be applied in the following order (specificity from highest to lowest):
#idName
img.className
.className
But when you use a specific class only for one specific type of elements (e.g. “className” only for IMG element), you can go with only .className.