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.
Related
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.
This question already has answers here:
What's the difference between an id and a class?
(17 answers)
Closed 8 years ago.
Lately I'm working with a lot of Wordpress themes. When I have to edit a particular element, I usually use Firebug to see the element's name so I can change the CSS. I think I understand the difference between IDs and Classes, Classes are used for a group of elements that you want to share the same styling, and ID is usually used for a single element.
Here's the thing, I'm seeing so many elements in these Wordpress themes that are only used once, but they are assigned to a class. A good example is the website logo. Isn't the logo only used once? Shouldn't it be assigned to an ID? Why is it always assigned to a class?
Needs change often. An element/style that today you think will only be used once may be used multiple times in the future. Maybe you will have your logo more than one time on your site (for example, on your about us page). Perhaps you may eventually incorporate a second search bar. There are very few cases where you know with 100% certainty that the style will only be needed once.
Here's a good read on the subject: http://oli.jp/2011/ids/
http://ryanfait.com/articles/the-difference-between-ids-and-classes/
Ryan says
"I take a different stance than most web designers when it comes to
using ID's and classes. The vast majority of CSS coders use ID's for
any elements that are simply used once on a page. However, I only use
classes to style my websites, but, when I want to use an element in
JavaScript, I use an identifier. From a presentational standpoint,
styling elements with classes looks exactly the same as styling them
with ID's, but the flexibility of classes offers a certain appeal even
if I don't plan on using a class more than once on a page. Also, when
I see an ID in my XHTML, it reminds me that there is some JavaScript
that refers to that element. It's up to you, but so long as you
implement classes and ID's properly, it is more or less a matter of
personal choice when to utilize one or the other."
id is a unique one, but when class its not, you can you one for many selectors
ID's are unique
Each element can have only one ID
Each page can have only one element with that ID
Classes are NOT unique
You can use the same class on multiple elements.
You can use multiple classes on the same element.
Any styling information that needs to be applied to multiple objects
on a page should be done with a class. Take for example a page with multiple "widgets":
There are some reasons why people prefer using classes instead of id's in CSS. (note that for javascript ID's are still commonly used).
The class element is re-usable on that page. This means that you won't have as much duplicated code with Classes as you would have with ID's.
Usually, IDs refer to something very specific, and abstracting would be tough
Any performance gains picked up by using id, is negated by adding any other selector to the left fo that id. Which mainly means that in most uses of id's you won't really have performance gains. (you could even have less performance than if you would just use a class)
Lecture about this:
http://screwlewse.com/2010/07/dont-use-id-selectors-in-css/
http://www.impressivewebs.com/css-specificity-irrelevant/
http://www.baldurbjarnason.com/notes/ids-in-css/
If you're new to web development, just use the simple rule:
If you're trying to apply style to a HTML element, use a class.
If you're trying to interact with a HTML element with javascript, use an ID.
You see more of classes because they can be reused and assigned to multiple elements.
However an id can belong to only one element at a time hence less of them.
Classes only appearing once:
Such cases like the one you identified, you may call them semantically incorrect as id is more appropriate choice for that but still it would work and it probably happens couple of times that we get to use class which only appearing once (may be while defining that class we are thinking that we can use it somewhere also but at the end we really dont), beside general habit another reason could be:
That class styling is also used somewhere else along with another class for e.g.:
.logo{
width:250px;
height:250px;
float:left;
}
.logo class is applied to logo <div class='logo'>...</div> But there is another element which also require same three properties of logo and some other also so one can reuse logo there also.
<div class='otherstyle logo'>...</div> this would apply the style of logo as well as otherstyle to it.
In some other words to sum it up. The cardinality of a class is 1...* so you can use it one and more than one time. But for id it is 1...1 you will and only use it only once.
Is p.error better or worse than .error?
I have read that element-specific selectors are bad and should be used only if really needed but noone seems to know why. I mean I do understand that .error is better for code reuse, but is there somekinda specific reason why I shouldn't address class with element always?
CSS selectors are read right to left. So p.error has one additional step to .error. This may result in a smaller set or not - depends on your markup.
However, this is a micro micro optimization. There is not going to be a performance hit unless we're talking about a massive amount of selectors.
Here's a great article on CSS selectors that elaborates on how they are evaluated : http://css-tricks.com/efficiently-rendering-css/
.error is more efficient than p.error .
To understand why this is more efficient I recommend you read this article over at css tricks.
no it's not bad, but it may not always be necessary
tools like Google's PageSpeed and YSlow! refer to these type of selectors as being "over qualified" perhaps that's where you're hearing the "it's bad" part from - reading material
take for example p#myid - an ID should always be unique on a page anyway, therefore there is no need at all to qualify it with the p element. an ID already has the highest weight when specificity is being counted so again it's totally redundant to add the extra part to try and add more specificty.
However with class names like your example it can sometimes definitely be desirable to add the qualifier as you may want the class to be re-usable on different type elements but have different properties depending on if it's a div or a p for example, the "qualifier" then makes the selector slightly more specific
.error {background: red; margin: 5px;}
p.error {margin: 2px;}
The code above means you can use the error class on any element and it will have 5px margins however if you set the error class on a p element the second selector is actually doing something, it's over-riding the first's margins but still getting the background color
So they do a job, but too often you see too many people over qualifying all their elements when it is not necessary.. for example if you're only ever applying that .error class to a p element then you wouldn't need the second selector.
The rule of thumb is to make the selector unique as quickly as possible starting from the right side of it.
Having a very specific selector will not amount to bad performance, but if there are a lot of declarations applicable for an element, then the performance will take a hit. The only concern otherwise is that it increases the no. of bytes to be downloaded for loading the stylesheet. Trust me, Every extra character in HTML passed is evil and will amount to lower page load speed.
During CSS cascading is applied by modern-day browsers, the following is the process that occurs for each CSS property for each web page element:
Gather all the declarations for the property from all the sources. This includes default browser styles and custom user style, as well as author style sheets. If there is more than one, proceed to 2.
Sort the declarations by importance and origin in the following order (from lowest to highest priority):
user agent style sheets (default browser styles)
normal declarations in a user style sheet (a user’s custom style sheet)
normal declarations in an author style sheet (web page style sheets; external, embedded, and inline styles)
!important declarations in an author style sheet
!important declarations in a user style sheet
The one with the highest priority wins. If more than one have the same priority then proceed to 3.
Sort by selector specificity. The one with the most specific selector wins. If no clear winner, proceed to 4.
The one that comes last in the source wins!
If the cascade does not set a CSS property on an element, then the browser will fall back to using an inherited property from the element’s parent (this only happens for some properties), otherwise the property is set to the CSS default value.
According to the above process, if you use a lot of more specific selectors, there would be a choice made after atleast 3 levels deep. Hence, the more the no. of declarations which might be applicable to an element, the lower the performance would be.
So, You must as specific as it makes sense to be.
The reason is specificity. For example...
+1 each access by class
+1 each access by tag
+10 each access by ID
etc.
So, if you have a class and a tag access, that style has a specificity of 2 (1+1).
Later, if you're trying to style all .error elements, but you have a conflicting style in the p.error elements, the higher specificity will win. This may cause some headaches down the line. That is why you may not want to always use tag+class.
(That being said, specificity solves many more problems than it creates, and is generally regarded as Pretty Awesome.)
As a general rule of thumb, the less selectors a browser has to evaluate the better.
p.error isn't necessarily "worse" than .error, if .error is used for multiple tags. e.g. div.error (see a foot note at the bottom).
But if it's only used on a paragraph anyway, then having p.error is just making the browser work harder i.e.
First it will have to find all elements with the class attribute error and then filter these by only having tags that are p.
Here is some interesting reading on Optimize browser rendering on Google's Page Speed site.
Foot Note
However if you need to use a class on multiple tags, it's probably best only to put in the css styles which apply to those tags instead of trying to separate it. e.g.
.error
{
color:red;
}
h1
{
font-size:2em;
}
p
{
font-size:0.8em;
}
<h1 class="error">Bad Heading!</h1>
<p class="error">bad!</p>
So that kind of defeats the need to prefix classes with tags anyway.
I hope this helps!
I'm wondering if there is any difference between div.class and .class as CSS selectors if there is only one tag (the DIV) with that attribute. Same thing for IDs: div#ID and #ID.
Any idea what, if anything, is the difference? For me, I use the class or ID in these situations; but only because it's quicker to type.
They are more specific, so long ones will override the shorter version if they conflict. div.foo will have a specificity of 11 while .foo has a specificity of 10.
Since they are more specific, you know exactly which nodename the class applies to instead of being a universal rule for all node names, this can help if you have a huge application with tons of elements that all have the same class names, it can lessen the time for you to find the element in the source/text editor.
There is only a VERY SLIGHT difference in specificity.
p#id is (0,1,0,1)
and
#id is (0,1,0,0)
in otherwords, the tag itself doesn't hold very much specificity at all compared to an ID, and relying on that kind of tiny specifity to overrule things is almost never needed in my experience.
More importantly, NOT tag-qualifiying selectors is more efficient for the browser to render.
Sticking to just a class or id, as you do, means that your CSS will still apply if the HTML tag is changed to a different tag.
Most of the time, this is probably exactly what you want — classes are there to allow you to add a custom layer of meaning on top of HTML.
In general, your selectors should be the minimum required to express your meaning.
Usually those longer selectors come in handy once the majority of the CSS has already been done. Sometimes you want to tweak a little thing here and there - say - differenciate between p.error and div.error for example. So instead of adding another class - and thus having to touch the HTML - you can simply add an element name to your selector instead, for more fine grained control.
No, there is no difference if you only have DIV tags of the specific class or ID.
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.