I'm trying to select an element which has two distinct classes, unfortunately these class names are partially randomised (The markup is out of my control) e.g.
<div class="thing1_abc thing2_def"></div>
Where the second part of the class name is random, as in, the abc and def parts will not be consistent between each page load.
The only thing I could think of was:
div[class^="thing1_"][class^="thing2_"]{ }
But it seems you can't use multiple class-attribute selectors in a single selector, is there any way to achieve this? Or any alternative that will select this element based on it's classes?
The ^= relates to the beginning of the whole class atribute string, that's why thing2_ won't be matched. You could use *= instead, like this:
div[class*="thing1_"][class*="thing2_"]{ }
But that would also match some_class_thing1_. That might still filt your needs, if you can be sure that such a class will never exist. But otherwise, I don't see a pure CSS solution.
Related
We have a modal and full page view of our application. For the modal, we attach a "modal" class to the body, so that we can select elements based on whether or not they are contained within this "modal" class.
Several of the items we need to target have IDs. Is it bad practice to select these items like so?
.modal #child-element-with-id { ... }
The above works perfectly fine in all the browsers I've tested, but someone on the code review is complaining about it from a code smell perspective.
I know IDs are supposed to be unique and shouldn't be nested, but doesn't this constitute an exception? To me it seems like the cleanest way to target the ID, instead of coming up with separate IDs for modal and full page views.
This will work, yes. However, if you need to reuse this style for multiple elements, you should create a class.
For example if you do:
.modal #child-element-with-id { /* same style */ }
.modal #child-element-with-id-2 { /* same style */ }
.modal #child-element-with-id-3 { /* same style */ }
Then you should be making a class to avoid style duplication.
To answer your question, the jury is still out and you'll have to decide if selecting a nested ID works for your use case :)
The only issue I could see that if you move the ID to a different element, this may cause confusion and be hard to debug, because your CSS expects the ID to be nested in a class.
Styling by ID is generally frowned upon. If you have the opportunity to edit the markup, why not add a class to those elements with IDs?
You may find that once you have introduced a highly specific selector (0, 1, 1, 0) you may end up having to add to it later for something even more specific – this is the scenario we try to avoid.
…instead of coming up with separate IDs for modal and full page views
I would reconsider this setup and add classes onto the elements with ID's. If you are already styling those elements by #id it's quite easy to swap the CSS selector to a class. If you find it's not easy to style those #ids now that they are classes - my point may already be proven :)
Hope that helps!
I know that to stack backgrounds on a selector I do something like
.selector{
background: url(url1), url(url2);
}
How can I add backgrounds when using different classes? (like a base class that will have url1, and another class which will have url2)
like
.base{
background: url(url1);
}
.selector{
background: url(url2);
}
but stacked
As far as I know, CSS is a set of key-value pairs. The key being the selector, the rule being the set of attributes associated to values inside the curly brackets. This forms a rule. If you stack keys, then you are basically telling that the attribute values are common for all tags which match the selector. However, if you want to give more values to the same attribute, it is ambivalent and I am pretty sure it is not supported in CSS.
EDIT: Imagine the interpreter having to look at each attribute of each rule and count the number of commas and check whether the number of commas matches the number of commas in the selector except value selectors. It would slow down the interpretation and would be nonsensical too.
Not sure if this is possible or if I'm just not asking the right questions, but I'm looking to apply a global rule for a set of classes that have different suffixes.
ie.
.gallery {} would like these rules to apply also to .gallery-1, .gallery-2, gallery-3 {} etc... Without having to add those actual specific classes to my stylesheet each time a new gallery is made.
Does anyone know if this is possible?
with thanks.
You could use the attribute selectors. Possibilities include:
[class|='gallery'] - matches all elements whose class attribute is exactly gallery, or begins gallery-
[class^='gallery'] - matches all elements whose class attribute starts with gallery
Note that I'm not clear what happens if your element has more than one class, as class="some-class gallery-1"
You can use wildcards with attribute selectors to do just that. Something like this should work for your case:
[class*='gallery-'] {
do:something;
}
See here for more info: https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors
Note the "Summary" section in the link above, it describes the different behavior of the "wildcard" symbols.
A simple alternative would be to simply apply two classes to your html elements:
class="gallery gallery-1"
Here is a very similar question and answer Is there a CSS selector by class prefix?.
Use CSS Selectors
For your example, you'll need this:
[class^='gallery']
(get all elements with a class name beginning with gallery)
I know we can provide styling and positioning in CSS for text box, text area, buttons etc. using "Class" , "Id" etc. attributes to identifying an element.
My question is:
How do we decide when to use a particular attribute?
Is there any advantage of using one over other (class vs Id vs other)?
Why do we have multiple ways of identifying elements? Why not have one standard way to identifying such as, lets say "Id"?
Thanks in advance
ID is used when we want a more specific selector than a class. A class can be applied to many elements, an ID only to one (a unique one at that). ID's are most specific and will (depending on your selector) gain precedence over a class. I would recommend reading up on CSS precedence: https://www.google.ca/?q=css%20precedence
You can't use ID everywhere because only one element is allowed to have a given ID, so if you want to apply the same style to five different elements, you'd have to create five different rules, which is pointless.
It's usually best to use a baseline definition for how you want certain element types to appear generally (links, lists, tables, etc.). Then if you have specific places where you want those elements to have different styles, apply a class to an element to identify that place ("navigation-bar", e.g.), and use custom styles to modify the behavior of elements within that area:
li {/* How you generally want list items to appear */}
.navigation-bar li {/* How you want list items to appear in the nav bar */}
Due to the way the styles "cascade", properties set by the second rule will override the properties set by the first because the second selector is more specific.
As far as why there are multiple ways available to select an element, it's because they're pretty much all useful at one point or another. CSS helps reduce maintenance costs because you don't have to repeat the same styling information in a bunch of different places. It can only do this if you can come up with a rule that makes it possible to match the elements you want in a variety of different situations.
The reason why we need various selectors (and not just one, using ID like you suggest) is that they are useful in different scenarios.
Element-selector (input, div, span). Useful when we want to apply some sort of styling for all elements of a certain type, indepently of its classes or id.
Id-selector. Useful when you want to apply styling to a single specific element.
Class-selector. Useful when you want to apply styling to multiple elements, indepently of what type of element they are (div, span, input). With class you can also combine styling of various classes by adding several classes to the same element.
If you were to use only the ID-selector, then you would violate DRY, since you would have to repeat a lot of CSS. Let's say you have five input-elements, that all should have the same styling applied to them. You would then have to explicitly write the ID-selector for every element:
#input1, #input2, #input3
{
/* Some styling */
}
If you later on need to add another input, you would have to modify your CSS and add a new selector for that input, so that the styling is applied to that element as well. In this case it would be better to either use a class that can be applied to all inputs. Or use the element selector and just apply the styling to all inputs.
/* Either of these would probably be more suitable */
.inputs {
/* Use a class to style the inputs */
}
input {
/* Apply styling to all elements of type input */
}
Think of an element's id like its passport number - it is UNIQUE to the one element, and can be used to apply styling to it only.
Each element can have only one ID (e.g. <div id="id"></div>)
Each page can have only one element with that ID
Think of an element's class like its nationality - it may be SHARED with lots of other elements. Therefore it is NOT UNIQUE.
You can use the same class on multiple elements. (e.g. <div class="class"></div> <div class="class"></div>)
You can use multiple classes on the same element. (e.g. <div class="classone classtwo"></div>)
When doing large projects, you may want one standard content wrapper, with different things inside it each time. In this case, the wrapper would be identified by 'class' and the things inside it by 'id'.
When applying multiple instances of CSS, the order of precedence is as follows:
Element -> applying generic CSS, for example to all 'divs'
Class -> applying generic CSS, to all elements of that class
Id -> applying specific CSS, to one element
Inline styling -> applying specific CSS, using the style="" tag within an element's tags
In CSS we can use both ID and class. is there any pros and cons if i use Class always instead ID in terms of Semantic, Web standards- W3C , SEO , Accessibility and future maintainability?
One big difference: in CSS, a class has a lower importance level than an ID.
Imagine that each specification in a CSS declaration added a certain number of points to that declaration's value. Let's say the points go something like this (totally made up, but whatever):
Tag name ('a', 'div', 'span'): 1 point
Class name ('.highlight', '.error', '.animal'): 10 points
ID ('#main-headline', '#nav', '#content'): 100 points
So, the following declarations:
a {
color: #00f;
}
.highlight a {
color: #0f0;
}
#nav .highlight a {
color: #f00;
}
are worth 1, 11, and 111 points (respectively). For a given tag, the declaration with the highest number of points that matches it "wins". So for example, with those declarations, all a tags will be blue, unless they're inside an element with the "highlight" class, in which case they'll be green, unless that element is inside the element with id="nav", in which case they'll be red.
Now, you can get yourself into tricky situations if you're only using classes. Let's say you want to make all the links in your content area blue, but all the links in your foo area red:
.content a {
color: #00f;
}
.foo a {
color: #f00;
}
By my previous (made up) scale, those both have 11 points. If you have a foo within your content, which one wins? In this situation, foo wins because it comes after. Now, maybe that's what you want, but that's just lucky. If you change your mind later, and want content to win, you have to change their order, and depending on the order of declarations in a CSS file is A Bad Idea. Now if, instead, you had the following declaration:
#content a {
color: #00f;
}
.foo a {
color: #f00;
}
Content would always win, because that declaration has a value of 101 (beating foo's 11). No matter what order they come in, the content declaration will always beat the foo one. This provides you with some very important consistency. The winners won't arbitrarily change based on changing orders in the file, and if you want to change the the winner, you have to change the declarations (maybe add a #content in front of the .foo declaration, so it will have 111 points).
So basically, the differences in values are important, and you get a lot of inconsistency and seemingly arbitrary winners if you just use classes.
I know i'm not the 'norm' here and i'll get thumbed down for this... but i use classes exclusively and only ever use ID's for scripting :)
This creates a clear line of seperation of designer and coder related tweaks and changes, which is very handy for us!.
Also we have some .NET web form coders (even though we are moving all sites to MVC) and as .NET controls take over ID's to script them dynamically using ID's for CSS is a pain... i'm not a fan of using #ct00_ct02_MyControlName in css files and even if i was changes to code can break the CSS! Classes works GREAT for this.
Some PHP libs others in the company are using also need to use dynamic ID assignment, this creates the problem here too. again Classes work GREAT here.
As more and more of these dynamic outputs and languages use up the ID's (for exactly what they are really intended for... identifiing an element to work with it) it can be more and more of a pain to work with IDs in CSS.
It's seems to me that everyone wants to use them simply cause they think they should, becuase they are 'there', i offer the idea that ID's are not there at all for CSS and their use in CSS is just there as an extra helper via the selector and their real use is scripting.
There has not been a single instance where i needed an ID for css use or even a single instance where it would have been eaiser.
But perhaps i'm just used to it and thats why? My HTML output is small, my CSS files small and direct. Nested elements work in all browsers as i expect, i dont have issues and can create complicated nicely rendered pages. Changes take mere minutes as i can apply multiple classes to an element or make a new one.
ID's for scripting, CLASS for css... works a treat.
Obivously there is no major issue (Even in a team of designers and coders) in using them both for css as we all get used to what we get used to :) but the way we work it outputs the expected results fast, and noone can step on anyones toes even in anonomous sharing enviroments.
My biggest one would be from the future maintenance point of view. Not only is it nice to know that a style is only used for one element on a page, but if you ever start integrated javascript into your page its nice to be able to access elements quickly using their IDs rather than try and access them by their class's.
If you're using a decent javascript library (like prototype or jQuery) then no, I can't think of any technical reasons why this would matter. However, it might help your own internal thinking and consistency to think separately about whether it is an attribute-like collective characteristic (=> class) or a specific item (=> ID).
Use id when an element is unique on a page and you always expect it to be. Use class when multiple elements will be assigned the value of the attribute. It's true that it may not make a big difference from a purely CSS perspective, but from the JavaScript or Selenium perspective, it's a big deal to be able to uniquely identify elements by their id attribute.
In simple we can define id and class as below
ID = A person's Identification (ID) is unique to one person.
Class = There are many people in a class.
Use IDs when there is only one occurence per page. Use classes when there are one or more occurences per page.There is no hard rule on when to use ID and when to use Class. My suggestion is to use class as much as possible for maximum flexibility, with the only exception being when you want to use Javascript's getElementByID function, in which case you need use ID.
IDs are good for elements that need to be accessed from JavaScript. But the IDs must be unique in the page according to w3 standards, that is:
you cannot have two <div id="Header"> in one document
you cannot have a <div id="Header"> and <p id="Header"> in one document
Class names are good for elements that do not need to be accessed from JavaScript (although it is possible to do so). One class name can be used for multiple elements, and one element can have more than one class names attached to it. Class names therefore allow you to create more "generic" css definitions, for example:
<div class="column">
<div class="column left-column">
<div class="column right-column"> -- all three can be in the same document
You can mix IDs and classes together.
To summarize: use IDs for specific cases; class names for generic cases; and cascad classes for elements that share some general properties but not all.
See following:
CSS Best Practice about ID and Class?
For SEO: It will make absolutely no difference to seo at all.
You should choose names that reflect the semantic content of that section. eg: id="leftMenu" class="footerNotes"
Don't use any underscores in your class and id names (common mistake).
The only difference between classes and ids, except for the fact that an id MUST be unique and a class does not, is that the browser can use an element's id for navigational purposes. For example, this page has a logo with id="hlogo". If you append to this page's url the hash #hlogo, like this https://stackoverflow.com/questions/1878810/is-there-any-pros-and-cons-if-i-use-always-css-class-instead-css-id-for-everythi#hlogo, the browser will automatically scroll to the logo.