I read this tutorial on using regular expressions with CSS selectors and am trying to extrapolate: Is there a CSS shorthand to do the following? I want to select all div's with class of "foo" that have either an additional class of "a", "b", "c", or "d".
.foo.a,
.foo.b,
.foo.c,
.foo.d {
/* stuff */
}
something like:
.foo[class~='a','b','c','d'] {} ?
It's not possible, currently (with the Selectors 3 recommendation). There isn't a full-fledged regex grammar for CSS, nor is there a way to crunch down parts of multiple selector lists.
Selectors 4 proposes a new :matches() pseudo-class based on Mozilla's original :any() implementation (see this answer for a bit of history):
.foo:matches(.a, .b, .c, .d)
Of course, don't expect browser support for this yet. I might even forget to update this answer when that time comes but... we'll see.
Maybe .foo[class~='a'][class~='b'][class~='c'][class~='d'] ?
No, your first way of writing it is the correct way. You can only search for one match at time with an attribute selector so the closest thing that's a mixture of your two methods is:
.foo[class~="a"],
.foo[class~="b"],
.foo[class~="c"],
.foo[class~="d"] {
/* stuff */
}
Which really isn't shorthand or anything :P The best way to select by classes is just the ordinary way with a .className. Attribute selectors are only really helpful for selecting other attributes, or if you have a class that begins with a certain word and are using css3. For example you could use something like:
.foo[class^="mah-class"]{ }
Which would match mah-class-a mah-class-b mah-classAHHH... etc
Related
I wonder why element[class="name"] seems to used primarily in responsive emails instead of the usual .class?
Also, unless I'm missing something, if an element has multiple classes for eg.
<span class="class1 class2"></span> then neither of these appear to work:
element[class="class1"] { }
element[class="class2"] { }
.. why is that?
element[class="name"]
This is attribute equals selector and it will select the element with exact value. When you have multiple classes the exact match is not there and it does not select. Using attribute contains selector or other wild card selector would get the element. Following contains selector would get elements that have class1 as attribute class's value. It will get element with class name class123 as well.
element[class*="class1"]
I wonder why element[class="name"] seems to used primarily in
responsive emails instead of the usual .class?
This article probably talks about this.
Attribute selectors are being used to avoid an unusual glitch in
Yahoo! Mail, reference
It turns out that Yahoo! Mail ignores any styles that use attribute
selectors, meaning that you can use these in your #media queries to
ensure that Yahoo! Mail doesn’t override existing inline styles with
your #media -defined ones. Read more over here.
This should be simple, but I'm having trouble finding the search terms for it.
Let's say I have this:
<div class="a c">Foo</div>
<div class="b c">Bar</div>
In CSS, how can I create a selector that matches something that matches "(.a or .b) and .c"?
I know I could do this:
.a.c,.b.c {
/* CSS stuff */
}
But, assuming I'm going to have to do this sort of logic a lot, with a variety of logical combinations, is there a better syntax?
is there a better syntax?
No. CSS' or operator (,) does not permit groupings. It's essentially the lowest-precedence logical operator in selectors, so you must use .a.c,.b.c.
Not yet, but there is the experimental :is() (formerly :matches()) pseudo-class selector that does just that:
:is(.a .b) .c {
/* style properties go here */
}
You can find more info on it here and here. Currently, most browsers support its initial version :any(), which works the same way, but will be replaced by :is(). We just have to wait a little more before using this everywhere (I surely will).
For those reading this >= 2021:
I found success using the :is() selector:
*:is(.a, .b).c{...}
If you have this:
<div class="a x">Foo</div>
<div class="b x">Bar</div>
<div class="c x">Baz</div>
And you only want to select the elements which have .x and (.a or .b), you could write:
.x:not(.c) { ... }
but that's convenient only when you have three "sub-classes" and you want to select two of them.
Selecting only one sub-class (for instance .a): .a.x
Selecting two sub-classes (for instance .a and .b): .x:not(.c)
Selecting all three sub-classes: .x
No. Standard CSS does not provide the kind of thing you're looking for.
However, you might want to look into LESS and SASS.
These are two projects which aim to extend default CSS syntax by introducing additional features, including variables, nested rules, and other enhancements.
They allow you to write much more structured CSS code, and either of them will almost certainly solve your particular use case.
Of course, none of the browsers support their extended syntax (especially since the two projects each have different syntax and features), but what they do is provide a "compiler" which converts your LESS or SASS code into standard CSS, which you can then deploy on your site.
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 need to apply a style on a recurring element which has a fixed prefix in its ID. e.g. for the generated ID old-price-520, old-price is the prefix, and the numeric suffix will vary.
How do I apply styles to these elements, or how do i refer to them using CSS?
Here's an illustration of what i'd like to do:
#old-price-* {
// some styles
}
div[id|="old-price"]
would select all div Elements with id = old-price-*
Handycap is it's performance which is pretty poor, compared to the power of the # id-selector. Also it has a lower specificity than the normal #.
edit:
fiddle
You can try to use CSS3 attribute selectors like this:
div[id^=old-price]
{
// some styling
}
However you will need to add some javascript for browsers that do not support it
you can do so with the 'begin-with' attribute selector in CSS3, like so:
[Attr^="value"]
and the concrete example would look like this:
*[id^="old-price-"]
there are probably more methods of achieving the same outcome, a quick search came up with this attribute selectors depiction for a quick reference.
You can use jQuery to do this with an 'Attribute starts with selector'
http://api.jquery.com/attribute-starts-with-selector/
I'm trying to find out what is the best practice for naming and casing css classes and ids, especially multiple word names.
So for instance, say I have a <div> that I want to name "character skills".
It seems like there are 3 choices: "characterskills", "character_skills", or "character-skills".
Which one of these is the industry standard for naming css classes and ids?
What's the best practice for splitting multiple words in css names?
Also is it a best practice to always use all lowercase for css names, because they are case-insensitive?
I tend to use the hyphenated style as well. I mainly use that style since CSS properties follow the same casing. Similarly, JavaScript functions and variables tend to use lower camel case. For example, to change a CSS property in JavaScript, you would type object.style.textDecoration, but in CSS, that property would be changed with text-decoration.
I use lowerCamel for class names and UpperCamel for IDs. This is quite important and I'm beating this old answer because IMO the hyphenated style should be discouraged, even underscore is better than hyphenated.
Why? Because every other language can't have hyphenated variable names. For e.g., your IDE may or may not pick up auto-completion properly. (My IDE can't, it's VI :P)
CSS being closely related to JavaScript, hyphenated classname also make it difficult to interop with JavaScript. Consider the following (contrived) jQuery:
// For each of the following class, perform a function
var funcs =
{
main: function(){ /* ... */},
toolbar: function(){ /* ... */ },
// Oops, need to use a quote because there's this hyphenated name
'customer-info': function(){ /* ... */ }
};
// Woot, a O(n^2) function
for(var className in funcs)
{
var func = funcs[className];
// maybe if we named it $('#some-selector')? The hyphen suddenly feels
// like some kind of operator to me. Makes me nervous :/
$('#SomeSelector div').each(function()
{
if($(this).hasClass(className)) func();
});
}
There's no clear advantage to using the hyphenated style other than subjective aesthetics. The disadvantages are that it stands out from every other programming language (OK, CSS may not be a programming language, oh well..) and that it is technically incorrect.
The correct (huh?) way to represent a space is underscore. Consider this phrase "a self-addressed letter," how can I convert the spaces?
a_self-addressed_letter (correct, preserves the original meaning)
a-self-addressed-letter (ouch! if we convert it back we get "a self addressed letter"!)
Also is it a best practice to always use all lowercase for css names, because they are case-insensitive?
I guess in this case, it's a best practice to always use PascalCasing because it aids readability.
I personally use the hyphenated style (i.e. some-class) but you should simply choose what you feel is best and be consistent. It is purely an issue of aesthetics.
I see the following casing styles a lot:
characterSkills,
CharacterSkills
But, at the end of the day it doesn't matter which style you pick. Just be consistent within your own app.
I've seen several different answers to this question, depending on who you ask. Ranging through all of the possibilities you mentioned and probably more. The one I see referenced most often, however is to use underscores (character_skills) and all lowercase.
The one answer thats always mentioned though and arguably more important than which method you choose, is to pick one and stick to it throughout. Keeping things uniform throughout allows you to avoid confusion and other problems later.
I use lowerCamelCase for classes, and UpperCamel for IDs, like so:
#HeaderLogo { ... }
.pullQuote { ... }
But it really makes absolutely no difference so long as you're consistent :) Oh, and try to stick to one-word class names where possible - you can always combine classes, like so:
.boxout { border: 1px solid; padding: 10px; }
.emphasised { font-weight: bold; }
.subtle { font-size: small; }
.boxout.emphasised { background: yellow; }
.boxout.subtle { color: gray; }
...which I prefer, as you can have your "base" classes hold core definitions, keeping your CSS smaller, and reducing the overall number of classes you have to remember when designing pages.
After reading examples and making my own mistakes, I landed on this solution for myself:
Use hyphens to show hierarchy e.g. #products-MainContent {} or #maincontent-Summary {}. To me this means that MainContent is a child of the products div.
Capitalise each word after the first element in the heirarchy for IDs. Use all lowercase for classes e.g. #summary-Statistics (ID) or .summary-statistics (class)
This works for me for now. I don't want to use hyphens to separate words because I think hyphens should show dependency/relationships. Also I don't want to mix up IDs and Classes because they look similar so I changed the case in which they were written.
I recommend using the BEM (Block Element Modifier).
Retrieved from its website:
BEM — Block Element Modifier is a methodology that helps you to create
reusable components and code sharing in front-end development.
For more details please visit its website documentation:
http://getbem.com/naming/