Take the following structure:
<div class='article article--yellow'>
<div class='article__headline'>...</div>
</div>
<div class='article article--blue'>
<div class='article__headline'>...</div>
</div>
If I need to make article__headline different for --yellow from --blue, should I do a CSS selector like:
.article--yellow .article__headline { ... }
Or, in the practice of minimizing selection-depth, is it valid BEM syntax to change the markup to this:
<div class='article article--yellow'>
<div class='article--yellow__headline'>...</div>
</div>
Because then I could select it using only 1 selector: article--yellow__headline.
I know that technically it would work, but I can't figure out if this is valid according to BEM methodology or not.
This is a perfect question and bem's faq actually answered it!
Can a block modifier affect elements?
If I have a block modifier, for
example xmas, and I want the elements within that block to also be
xmas themed, how would it be best to do it.
Does a --xmas suffix for every element seem necessary? Or would this
be the one use-case for nesting (e.g. block--xmas block__elem { ...
} ?
However in general BEM recommends to avoid nested selectors, this
is the case when they are reasonable.
When creating the nested selector, you declare that one entity depends
on another. As BEM introduces independent components, such an approach
is not suggested when we are speaking about 2 different blocks.
But when it comes to a block and its element, they are not of
equivalent meaning. By it definition, an element does not make any
sense outside its parent block. So, an element is a block-dependent
entity. Assuming this, it is quite normal and logical that an element
is affected by the block's current state.
So, this is quite a pattern in BEM to code
.my-block--xmas .my-block__button {
/* Jingle bells, jingle bells, jingle all the way.*/ }
So the answer should be your first approach
.article--yellow .article__headline { ... }
I don't think that two levels is too deep to assign specificity of .article--yellow .article__headline. Technically, .article__headline will never occur without an .article--yellow color modifier anyway.
Although the class names get lengthy, BEM allows you to easily-self document (assuming whoever comes after you understands these concepts too). Also, to me BEM components are not supposed to influence each other, as detailed here.
Related
If I have a container and a list of item, I might have the following HTML markup:
<div class="container food foodcontainer">
<ul class="list foodlist">
<li class="listitem fooditems"></li>
...
And I can style them two ways (assuming using plain CSS and not less/sass or any other helpers). First, like one normally would do:
.food { /* style */ }
.food .list { /* style */ }
.food .list .listitems { /* style */ }
Or, I can simply reference everything by a verbose, descriptive class name:
.foodcontainer { /* style */ }
.foodlist { /* style */ }
.fooditems { /* style */ }
No more cascading relationships! Is there a reason not to do this for everything (such that every element is referenced by a single class/id name)? I (and people working on the same codebase) simply do not find either to be that much better in readability; if anything, we find unique and direct names easier to grasp and also easier to search for.
There was an ancient article that generally recommended shorter, more unique selectors, for performance; in its more recent update, it's said that overall the performance has changed for the better. But how much better? Is the shorter way still faster?
.food .list { /* style */ } targets only elements with list class that are within an element with a class food.
.food > .list { /* style */ } targets only elments with list class that are direct children of elements with a class food.
.list { /* style */ } targets any elements with the class list, regardless of their parent elements.
Generally, if you want to make sure you're only targeting an element within a specific element and not any other elements that might have the same class, use the first or the second of the above, depending on your needs.
Of course, you could also give unique classes to them to avoid chaining them, but IMO there's just an unnecessary hassle of remembering which classes you've already in use. Also, I think it helps with readability, when you chain them instead of coming up with unique classes - then it's easier to see within which elements these rules apply.
I wouldn't worry too much about the performance with either of those - unless you have massive sites.
You can read about the CSS selectors here.
Well you could give a class to every element, but the point of the cascading relationships are to prevent having to give a class to every element.
For example:
a{ /* style link elements some way */ }
.some-div a { /* but in some-div they should look differently }
In this case you only have to set 1 class on the div. Else you would have had to give every link element a class in your html, which is kind of counterproductive.
Using relations you can be a lot more generic and avoid getting to the point where you end up with names like header-logo-nav-link-first. You would have to remember that class, but you would also have to write it in every element. Ever seen a footer with 50+ links? ;)
Also the more specific you are with your selectors the more priority your styling gets.
Very interesting question. Essentially, you have identified two dimensions to your class architecture. The first is the food dimension, which has a semantic meaning, and is particular to all things related to food. The second is the list dimension, which is a layout dimension, and is particular to all things related to lists and their layout.
This is a very clever way of breaking down classes. It helps prevent rules having to do with food from "leaking" into rules having to do with lists and vice versa. Your HTML becomes a clean orthogonal combination of classes from groups of classes with different meanings. In my mind, this is ideal. It follows a particular CSS design philosophy of combining smaller classes in different ways, which promotes re-use and improves readability. The alternative is "kitchen-sink" classes which are harder to re-use and harder to read. This will tempt you to use pre-processors with features like #extend, and things will go downhill quickly from there.
The technical term for defining singleton classes is "hyper-targeted". An example id Food__orange-disabled--listitem. If you go down this route, you will spend the rest of your life writing and rewriting these bizarre-looking class names. Every single change will require changes to both CSS and HTML. Proponents of this approach claim efficiency as one reason to adopt it, and this might have been an issue five years ago, but as you mentioned, today's browsers handle reasonable amounts of nested selectors without breaking a sweat.
I'm revisiting this question as I found newer and more recent articles and references.
In short, there should be little reason stopping one from using non-nested names. In fact, it might even help with both performance and maintainability.
BEM (and other similar naming schemes) tackles the maintainability issue.
And, class-centric styles help with performance.
I also want to add a few more explanations to why some of the reasons given in the other answers, or what I've seen being said else where, doesn't quite apply to argue against the case.
"This is not how CSS works."
It is true that CSS has nested relationship available, naturally as its name suggests, but that itself doesn't become the reason why we must or should use it.
"Nested relationship is easier to maintain."
This is only a "maybe" depending on the code style. Say, we have a style sheet like below:
a { /***/ }
.some-div a { /***/ }
.more-div a { /***/ }
And, we have a link somewhere in the template:
<div class="some-div ...
<div ...
<div class="some-other-div" ...
<a href="...
Now, when we look at the link in the template, we see a tag a with no classes. What styles does it have? Well, we have to go to the style sheet and search for a, and there will be many, many a's, and they can be nested arbitrarily deep.
This is just like "magic numbers" in other programming languages; the only difference is that instead of a number constant we have tag names. Searching for a single a is like searching for 3 in source code; we have to infer most information from the context.
And there is no way to do a quick search for the css selector because we don't know which parent in the ancestry tree is used in the style sheet. It could have been .some-div a or .some-div .some-other-div:last-child a.
Instead, if we classed the tag itself (e.g. <a class="some-div-link-class some-other-class" ...). It will just be a single search away.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I am working with other developers and as much as possible, I want them to understand the HTML/CSS code I wrote when they take over a particular project.
So, I have this simple snippet.
<section>
<div class="twocolumn">
<div>
<p>Hello</p>
Press
</div>
<div>
<p>Nice one!</p>
Click
</div>
</div>
</section>
To target inner elements in this code, which is better practice, to use selectors that begin from the outermost element (section) so that another developer will understand the "arrangement" of the elements as such:
section > div div:nth-child(1) p + a {
...
}
or should I make use of the classes like this:
.twocolumn a {
...
}
Which do you think is easier to read (for other developers)? What are the pros and cons for each process? Can you give other examples?
First off, your selectors don't tally. .twocolumn a by itself will match both a elements since you didn't specify to look only in div:nth-child(1).
That aside. Remember that the sole purpose of combinators in CSS selectors is to establish relationships between two or more elements in markup. So a sibling combinator says "this element must be a sibling following that one", a descendant combinator says "this element must be contained within that one", and a child combinator says "this element is a child of that one". If you do not need to enforce a specific relationship between two element (typically this comes from assumptions you make about the structure of your page), then you probably do not need to specify that many elements in your selector.
Taking your snippet for example: if you can guarantee that every inner div within that structure has a p followed by an a, you can leave out the p +. You only need it if a can appear elsewhere and you want to make sure you only target a if it directly follows p.
Next, if you can guarantee somehow that every section > div will have the class .twocolumn, then you can just use the class selector. I find that really unlikely given what the class name is supposed to describe, but assuming that it is the case, then if you want to select the first a only you will need div:nth-child(1) at least:
.twocolumn div:nth-child(1) a {
...
}
I can't offer much more general advice because it really depends on your requirements and what you are working with. But I will say that you should keep a balance, i.e. don't rely completely on the structure of your markup, use classes and IDs to point to key elements where possible. As mentioned in another answer, you want to avoid tightly coupling your CSS and your HTML causing you to have to change your selectors to reflect any potential changes in the HTML structure.
But do still account for a small set of possible variations in the structure, like with the p + a example I mentioned above, so you don't end up overusing classes and bloating your markup unnecessarily. Web applications are so dynamic these days, and CSS provides a reasonably potent syntax for you to use, so don't be afraid to use it and to educate others about how it works.
Short answer: never.
Well not never exactly. The more complex your selectors are then the more coupled your CSS code is with your HTML. Change the HTML and then you must reflect the changes in your CSS selector code. Back and forth for each change means more manual work to ensure your design isn't broken.
Ideally you want to use as many CSS classes as you can with no more than one level of child selectors. Best to use the > operator to target direct children rather than relying on the ancestor selectors.
This is my opinion obviously, but I have been developing websites for over 10 years. A good philosophy to follow (where I learned most of this from) is from SMACSS.
Keep in mind that it isn't always about markup. There's a break-even point between clean markup and sane CSS code. I've just found that by using multiple CSS classes then you have the maximum about of reusability.
As general best practice, less specific selectors are better. In this case, you probably wouldn't want to target EVERY <a> tag inside your .twocolumn div. A more specific selector would most likely be best, depending on what you're actually trying to do. If possible, you should add a class to the <a> tag and target .twocolumn a.classname.
The more specific selector the faster it will be handled.
In this case:
section > div {}
style resolver will look on the element and its immediate parent. That is O(1) computationally complex task.
But this one
section div {}
in worst case will have O(d) complexity, where d is a depth of DOM tree.
In CSS I understand that you use ID if you're targeting a unique element and use classes for general targeting of a group of element. I am maintaining a site where i have to clean up some of the code (html + css), I notice that the previous programmer didn't use any ID for all the element instead he used classes even for unique elements.
So, what's should be an advisable approach, Should I just use classes and follow his coding style, avoid using ID for the elements or should I replace them with IDs and use ID for appropriate elements.
In css, in my understanding, classes can also be used like an ID where you can just target a single element (eg. .footer vs #footer) and is just a matter of preference.
#header { background: #ccc; height: 150px; }
#content { background: red; height: 200px; color: #fff; }
<div id="header"><h1>Header Area</h1></div>
<div id="content"><h1>Content</h1></div>
<div id="header"><h1>Footer Area</h1></div>
notice #header was mentioned twice in the id and css rule applies to the two elements.
IDs behaves like Classes (http://jsfiddle.net/79GsY/)
.header { background: #ccc; height: 150px; }
.content { background: red; height: 200px; color: #fff; }
.footer { background: brown; height: 150px; }
<div class="header"><h1>Header Area</h1></div>
<div class="content"><h1>Content</h1></div>
<div class="footer"><h1>Footer Area</h1></div>
Notice that there was no ID used here.
Classes behaves like ID (http://jsfiddle.net/qHEJd/)
Please enlighten me with this matter. Thank You.
It's a matter of semantics. You use IDs to identify an element, for instance to distinguish multiple forms on a page, or as link targets. They have a meaning to the markup.
With classes, you set a classification for things, you don't really give them a meaning. It's not like you're grouping them together or anything.
So it's perfectly fine if only one element on a page has a certain class. That doesn't make it "unique".
An ID must be unique, a class can be used several times.
Personally I use IDs to name different sections of a site. IDs always describe what something is, never what it looks like. Examples of common IDs for me are #header, #footer, #post-comment etc.
Classes, on the other hand, are used to categorise similar elements. Both CSS and JS can then target a specific class. Examples of classes are .button, .icon etc.
Personally I don't use classes much at all but prefer to use SASS #mixins as they keep the HTML clean from design related class names.
In this instance, there's very little difference between using class names or ID. There is argument that using an ID in CSS will allow for minutely-faster processing, but it's such a tiny difference to be negligible.
There isn't any reason why you should spend the time modifying the previous developer's markup as long as it is valid (ie: no repetition of IDs) and works. Modifying classes or IDs/etc may well cause non-desired effects (particularly if the JavaScript is tied to those same DOM elements).
The only difference when it matters if you use class or id is if you multiple instances of that element. Say, you had a header/content and footer, you know you're going to have only singleton instances of these and so I'd use an id.
However, if you have two headers, so:
<div id="header></div>
<div id="header></div>
This does not comply with HTML standards, and so I'd use:
<div class="header></div>
<div class="header></div>
In base, if it's a single instance of that element, use an id. If you know you're doing the same operation more than once on an element, use a class. This is also the standard rule for CSS, to a degree.
You should always keep in mind that ID's Should be unique , if you have unique element, you better use ID, if not use class
quoting from w3c page -
What makes attributes of type ID special is that no two such
attributes can have the same value in a document
http://www.w3.org/wiki/CSS/Selectors/id_selector
I would prefer to use ID for the Unique element and Classes for the group of element.
Because,
When you are using IDs for the unique element DOM will search Tag with tha ID and will stop its searching as soon as it finds that Tag.
On the other end if you choose class for the unique element it would work same as IDS but DOM will not stop its searching even after it finds that Tag. It will search the whole page to find any other Tag with that class.
For the Group of Elements, we can't use IDS hence the using Class is the obvious Choice.
Hope this clear your doubt. Let me know if i am missing something.
The odds of it making any real difference to the site are near zero, so it's up to you. It's a style preference.
I think your question is mainly about the application of CSS styles to the elements, as opposed to scripting. When the CSS is being applied to the elements for styling purposes, I believe it makes literally no difference (other than specificity stuff) whether you use class selectors or ID selectors to specify the styles for the elements. Style application is done by taking the element and matching it against rules, not taking rules and finding elements that match them, if you see what I mean.
On the scripting front, though, for completeness: If you're looking up these elements with jQuery using CSS selectors, an ID selector may be very marginally faster than a class selector to find a single element in a very large document. That's because $("#someId") ends up being a call to document.getElementById which the browser can do efficiently because it knows that there will only be a single match. In contrast, $(".someClass") ends up being a call to querySelectorAll, which has to keep searching through the entire document (barring that search having already been cached by the selector engine, of course) even after finding one element, in case there are others.
But again: The odds of it making any real-world difference are virtually nil.
And a very minor point: Every element with an id creates a property on the window object with that id as its name (e.g., <div id="foo"> creates a foo property on window). Creating a lot of properties you're not going to use is a teensy tiny ipsy little bit of unnecessary work. ;-) But to call that premature optimization is to dramatically underestimate how premature it is (and dramatically overestimate the amount it optimizes). E.g., this is just trivia. :-)
To what extend should I be attempting to use other CSS selectors instead of element IDs/class names or vice versa.
For instance: body > header nav ul+ul { ... } when I could just do #socialnav { ... } to achieve the same thing.
Example HTML code being (obviously there are headers with child navs elsewhere in the code):
<header>
<nav>
<ul>...</ul>
<ul....</ul>
</nav>
</header>
What is the consensus on this? I mean, I find it manageable doing it using CSS selectors, but is there a disadvantage?
Your first guiding principal should be to keep the markup semantic. Your markup above is a great example of this - you're using header, nav, and ul tags in semantically meaningful ways.
Your second guiding principal should be to maintain separation of concerns (e.g., content and presentation). If adding a class names or id's to your markup does nothing for you semantically and you're able to craft CSS selectors w/out them, then you should avoid adding extra noise to the markup.
Sometimes, however, class names and id's are very useful (not just in CSS but also in JavaScript), so they have their place. Just don't resort to them if they're unneeded and are therefore adding unnecessary clutter to your markup.
It's up to your preferences.
I find it not wise to use body > header nav ul+ul, because a small change in your document structure, and you have to rewrite the CSS selector.
Use .classselectors and #id-selectors for elements which aren't an incredible important part of the main document, and use #one-special-item > ul > li > a:hover span to select the more specific elements.
Generally I try and avoid ID selectors in CSS.
I find it a lot easier to deal with classes than using IDs.
IDs can cause issues later on down the line if the markup is used in a Server-Side application, such as ASP.NET, where the IDs are rendered as something different to how they display in the markup.
However, ID selectors do take priority over class selectors:
http://jsfiddle.net/wcLrF/
You should write your stylesheets as rule sets for your site.
If you are writing a style which is you want to to work with a single specific piece of content, then it is good practice to reference that element's ID.
If you are writing a style which is part of your general site look and feel, then it should be written to reference tagnames and/or classes as much as possible.
There will be times when the actual html code is such that it becomes hard to follow those rules, but if you try to stick to that in general then you'll be okay. You may also need to bend your rules if you need to support older browsers (cough, IE, cough) that don't support all the CSS features that you'd normally want to use.
So yes, I would say that the way you've done it in the question is the recommended approach.
Using IDs and Classes as selectors is much faster than using normal css selectors. Some also argue that you should ONLY use classes because they encourage reusability in your stylesheets.
Here's a really good article about Object Oriented CSS: http://coding.smashingmagazine.com/2011/12/12/an-introduction-to-object-oriented-css-oocss/
Ive been wondering... in CSS are there any differences between creating a style class and applying it an element, or creating a style with the #elementId notation (apart from being able to assign a class to different elements)?
For example...
#div1
{
background-color: Yellow;
}
<div id="div1">
Hello world!
</div>
Or
.div1
{
background-color: Yellow;
}
<div class="div1">
Hello world!
</div>
Thanks! :)
An ID must be unique in a document. Classes can be used in any number and combination. So you can use one class on multiple elements and multiple classes on one element.
One other difference; id-selectors are more specific than class-selectors, so I believe they will "trump" any other selector that exists. You can use "important" to do the same thing, but and id selector may be easier.
But id-selectors should be used sparingly...
Many classes can include a given "class" while only one element may be identified by a given ID. If you need to locate an unique Element use ID, otherwise if you wish to mark many elements that are basically the same but in different spots in your html use 'class'.
You sort of answered your own question, they are just mechanisms to 'identify' elements.
using #elementID applies only to the element uniquely identified by that id. a class can be used by multiple elements
there is however an order of precedence. selectors using the id have greater weight than selectors using class and when there is a collision the #id selector will take precedence
edit: see http://kiribao.blogspot.com/2008/03/css-selectors-precedence-and-ways-to.html for more detail on selector precedence
edit: also see the w3c specs at http://www.w3.org/TR/CSS21/cascade.html#specificity
Performance or functionality-wise, there is no difference [citation needed].
The only real difference is semantic, if you are working on a single node with a unique ID, or if you need a reusable class marking several nodes.
There are some differences:
Uniqueness
IDs must be unique, classes can be repeated. This is logical if you look at their expected usage.
Usage
IDs should be used to denote large sections of a website (e.g. #header), or unique elements that are accessed via Javascript (e.g. #killSession)
Classes should be used for reusable parts.
Specifity
IDs get assigned a specifity value of 100, while classes are only worth 1.
So this rule:
#id .class
Is worth 101 points.
This rule:
#id #id2
Is worth 200 points and will always trump the #id .class rule (regardless of the source order).
Performance
Performance wise, getting elements by ID is always faster than class, especially when talking Javascript. I'd love to see someone add some cold hard numbers to this.
Discussion
An interesting discussion about the performance of selectors can be found at Shaun Inman's blog.
The usage of classes is debated in Jeff Croft Applying OOP concepts to CSS
Classes are to group together elements which share similar functionality (for scripting) and/or layout (for styling). IDs should always be unique identifiers for elements.
A good example for something which should have an ID is the content area of your document, which is common to use the #content ID for. Classes are good for anything else which may occur twice in your document, such as headers which should have special markup or behavior, or links which should open a lightbox instead of the normal "go to URL" behavior.
HTH.