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 2 years ago.
Improve this question
I frequently need to address generic elements inside some specific sections of a page. I find this approach most easy to understand in terms of what any rule is affecting:
.shop > .products > .product > .description > .warning {
color: red;
}
But I often see this:
.shopProductsProductDesc > .warning {
color: red;
}
Does it really matter which approach is taken?
It really depends on the problem you are trying to solve.
The selector .shop > .products > .product > .description > .warning to my understanding would be used for two cases:
You have multiple warning elements but you only want to select the elements inside your description and there are other selectors used for warning that you don't want to overwrite.
You need to overwrite a previous selector that is less specific. Ex. .shop > .products > .product > .description .warning
The other selector .shopProductsProductDesc > .warning is less specific than the first one but assuming the container of .warning has those two classes .description.shopProductsProductDesc then the outcome would be the same as the first one.
CSS is all about specificity, if your selector is more specific than the last one used the properties would change. This is why you have to be careful if you are using specific selectors because your last option to alter the properties would be to use !important.
I hope this helps to clear things out.
After trying a few different styles, I think that personal preference (or a set standard if you have collaborators) is really the way to go. I prefer the second version, but the first one is also quite legible.
If you consider efficiency of what the browser has to do under the hood to render CSS styles, BEM-style for example, is usually the ultimate winner as it is the most lightweight for the browser. I use BEM for some layout/common elements.
In real life unless you are doing something seriously wrong, modern browsers and devices make this difference of CSS parsing and rendering somewhat negligible. But that is if you code everything well.
I've worked with spaghetti CSS codebases that could take minutes to render all SCSS (it was a huge codebase, but a few files were big bottlenecks).
It matters because of specificity. The first style rule will always override the second, regardless of where they both appear in the stylesheet, because it is more specific (basically it has more class selectors in it).
That said, the first rule is a nightmare from a maintainability perspective, for a number of reasons:
It makes code incredibly hard to read and understand
It's harder to override (as we have seen).
If you change the structure of the HTML, it will break
You can only reuse it if you mirror the structure of the HTML exactly.
It's also bad from a performance perspective. When browsers are matching an element to a style rule they read each selector right-to-left and keep going till they either find a match or can exclude the rule. Therefore, the more simple the selector is, the faster a match can be determined. If a selector consists of just a single class name, the browser can match the element with the style rule more quickly than if it has to search upwards in the DOM tree.
The second rule is better, but optimal would be something like the following:
.shopProductsProductDesc--warning {
color: red;
}
This solves all the problems above, and it's long enough that there's unlikely to be name clashes elsewhere, (though obviously not impossible).
In general, nesting selectors in CSS is bad practise, in my opinion, and the best CSS methodologies are those that have ways of avoiding this, e.g. BEM, CSS-in-JS.
According to my own experience, the second option is often best, not for direct technical reasons (in fine, it will perform the same), but rather for UX consistency and code maintenance.
The first option produce an "heavy" selector, which will be harder to override. It can be wanted, but it is often the sign of an overall messy CSS, because if everything is overconstraint, it is less easily reusable/extensible.
From my understanding of CSS and frontend reusable components, you would always only need two levels.
The style of your warning component (no size, no margin, size depends on where you will display it, and margin is position, only internal design here):
.warning {
//Your design here
font-size: 1.5rem;
font-weight: bold;
color: orange;
}
And the positionining and variants inside containers:
.container > .warning {
//This is an example.
position: absolute;
right: 0;
border: solid 1px red;
}
Having long CSS selectors will make things more complex, hard to follow for your teammates, and hard to override because you will probably need a longer CSS selector, and it never ends. Plus, you will get an heavier bundle at the end.
If you want an efficient UX, the UI shouldn't be that different everywhere, so you should not need to have that many variants of the same component. Otherwise, maybe you need multiple different components, but you certainly want a simple and efficient UX, and that often goes with not so much visual concepts, so you must avoid tons of variants.
Related
I am building websites for a while, and I have a question about CSS I can't really rid over. So there is that frequent situation when multiple classes affect a DOM element, and both classes declare the same properties. For example:
.first {
color:white;
}
.second {
color:black;
}
I know that if I have an element with class="first second" in that the text will be black. If I rather want it to be white, I have several options:
Using !important: I know this one is handy and I use it, but sometimes, if I use it too often, my CSS may become messy. I mean, multiple !important's can result the same basic situation.
Reordering the classes inline: if I am correct, which class comes first, it will be the priority one. This is nice, but i often work with environments where I can't affect that. Secondly, this is not a global but a local solution.
Reorder the CSS itself: well, this sounds interesting, but if I work with many stylesheets (and I do), it is hard to track, especially when it is WIP.
Actually what I am looking for is some workaround like z-index but for priorizing which class is stronger. Because I can't really find anything useful in this topic, I am just curious maybe it is a user error, and you guys know something I don't. How do you manage this? What do you suggest?
class="first second" is the same as class="second first". The priority is based on the position of the declarations in your css and not in their position on the html element.
So, if you want priority of a class against another, put the top priority class LAST on the css file.
.first {
color:white;
}
.second {
color:black;
}
in this example, class second has always priority over class first. This happens because browser scans through the css top-to-bottom and always applying the rules of matched classes that finds. So, the last matched class has priority over the previous matched classes.
see this fiddle: http://jsfiddle.net/5c29dzrr/
At the same specificity level, the CSS selector that is furthest down the stylesheet will be applied. So in your example, if you wanted in that situation to have the element with the white colour you would have to order your properties like so:
.second {
color: black;
}
.first {
color: white;
}
The order of the classes in the HTML tag is not important; it is the order in which they appear in your CSS.
The better way to handle this is to go with some better naming convention such as BEM or SMACSS so that you don't have the issue of conflicting class names.
Edit: It might be worth reading up on specificity and the cascade for a better understanding of this. I found this calculator to be pretty handy in determining which rules will take precendence, although these days you can just use the developer tools to find out that information.
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 8 years ago.
Improve this question
In the following article I read that one should try reduce the number of selecetors.
Article: use less selectors
I'm wondering if writing LESS and I'm using a lot of nesting to group parent and child elements, will that generate bad CSS code in the end?
LESS
.wrap{
width: 100%;
height: 20%;
background: green;
header{
background: blue;
h1{
color: red;
}
}
}
I'm using a lot of nesting to group parent and child elements, will that generate bad CSS code in the end?
In a word, yes. In the long run this will give you highly specific, unmaintainable CSS. Let 's have a look at what your example will produce for the h1 style.
.wrap header h1{ color: red; }
So what you've ended up with here is a very specific CSS selector, that isn't really necessary. You could, for instance, just have
h1 { color: red; }
or use a class on the h1
.title { color: red; }
Why is specificity bad?
So imagine, 6 months later another developer comes along and they need to change the color of a h1, but just one of them.
First they try to add a class to the h1
.new-color { color: blue; }
But the colour doesn't change because the original CSS is so specific. So they have to do this
.wrap header h1.new-color { color: blue }
or worse still they may do this
.new-color { color: blue!important; }
And then what happens when other changes need to be made? As you can see very quickly and very easily you can end up with unmaintainable CSS, that will have everyone pulling their hair out.
Performance
People usually negate performance when it comes to CSS, but it is always good to know what is going on when a page is rendered. CSS is read from right to left. Using your example
.wrap header h1 { color: red; }
This means the browser engine will search for every h1 and check if they have a parent header and then if that has a parent class wrap. If so it will apply the style. A low specificity makes the rendering process a lot simpler.
Summary
So to sum it up, nesting, whilst it may seem great keeping your code nice and readable, should only be used when absolutely necessary. It's very easy to forget what the CSS that is actually being produced looks like. Before you know it you'll be in nesting hell.
Languages like LESS or SASS give you more flexibility in declaring your style rules, and that can be good or bad depending on how you use it. The more flexibility you have in a language, the more you need design patterns and good practices to avoid making things worse than they were before.
LESS doesn't require that you always nest. You can always use CSS of course, and if you are applying a style to all p it might be better to define it globally, than to call mixins to obtain the same result on several nested ps.
But LESS and SASS do allow you avoid duplication, to write code that is clearer and easier to maintain, and other problems caused by the code duplication required by CSS.
I know about mixins and parametric mixins. What we are looking for is a way to make any general purpose selectors in CSS / LESS into a mixin.
Eg in Twitter BootStrap, we have here
.navbar .nav > li {
float: left;
}
If I have to use it in a class say .mynavbar I want to be able to do this
INPUT->
.mynavbar {
.navbar .nav >li;
}
OUTPUT->
.mynavbar {
float:left;
}
Now I know this can't be done with the current version of LESS as the compiler flags a parser error. I wanted someone to help me out on changing the source code of less.js a little so that this is workable.
I've managed to reach the source code for the mixin parser. I've tried changing the RegExp there, but it interferes with other parts of the parser. I know we have to make only a few changes because, instead of just accepting .mixin and #mixin we have to accept any mixin like tags / attribute selectors like input[type=text].
It is currently needed for the development of a UI framework that uses Bootstrap. Unfortunately many places in bootstrap are littered with direct tag selectors instead of ids and classes.
This is possible since version 1.4.0 (2013-06-05) of LESS that include the extend feature. Based on the original example
.navbar .nav > li {
float: left;
}
.mynavbar:extend(.navbar .nav > li) {}
compiles to
.navbar .nav > li,
.mynavbar {
float: left;
}
Documentation here and discussion & example use for the original question here
EDIT: Added Code Sample
First off, I would strongly discourage doing such things. Instead, try to use the power of CSS and build your HTML such that the bootstrap rules apply, for example. Anyway, since you asked for it, here is the solution.
The problem is not the complexity of the selector, or the child rule, but the tag name selector part (i. e. the li). So, what we have to fix is the mixin parser only matching classes and ids. I guess we would not want to tamper with the first class or id test, since that is probably needed to distinguish mixins from normal CSS rules (although the tests run fine with that check commented out). (Actually, there is a parser preference in action, and the only thing tried after mixins are comments and directives, so we can safely remove that check as well). However, we can easily allow tag names in later parts of the mixin selector by adding a question mark after [#.] in the matching regular expression. So
while (e = $(/^[#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/)) {
– i. e. line 825 – becomes
while (e = $(/^[#.]?(?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/)) {
The test cases still run through fine, afterwards, but subtle breakage my occur, so be cautious.
Edit: There is a GitHub Issue for the same problem. Apparently the less folks rather want the mixin feature to be more narrow and function-like, instead of allowing a more flexible … well … mixing in of rules. With regard to the CSS output, that's probably reasonable.
I know that in a stylesheet div#name and #name do the same thing. Personally I've taken to using div#name for most styling I do, with the reasoning that it's slightly faster, and means that I can identify HTML elements more easily by looking at the CSS.
However all of the big websites I seem to look at use #name over div#name (stack overflow included)
In fact I'm finding it very difficult to find many websites at all that use div#name over #name
Is there some advantage to doing #name that I'm missing? Are there any reasons to use it over div#name that I don't yet know about?
Since the div part of div#name is not required (because ID are unique per page), it makes for smaller CSS files to remove it. Smaller CSS files means faster HTTP requests and page load times.
And as NickC pointed out, lack of div allows one to change the HTML tag of the element without breaking the style rule.
Since ID's have to be unique on the page, most ID's you'd run into would only ever appear once in your style sheet, so it makes sense not to bother including what element it would appear on. Excluding it also saves a few characters in your style sheet, which for large sites which get visited millions and millions of times a day, saves quite a bit of bandwidth.
There is an advantage to including the element name in the case where a division with ID "name" might appear differently than a span with ID "name" (where it would show a division on one type of page and a span on another type of page). This is pretty rare though, and I've never personally run across a site that has done this. Usually they just use different ID's for them.
It's true that including the element name is faster, but the speed difference between including it and excluding it on an ID selector is very, very small. Much smaller than the bandwidth that the site is saving by excluding it.
a matter of code maintainability and readability.
when declaring element#foo the code-style becomes rigid - if one desires to change the document's structure, or replace element types, one would have to change the stylesheets as well.
if declaring #foo we'll better conform to the 'separation of concerns' and 'KISS' principals.
another important issue is the CSS files get minified by a couple of characters, that may build up to many of characters on large stylesheets.
Since an id like #name should be unique to the page, there is no reason per se to put the element with it. However, div#name will have a higher precedence, which may (or may not) be desired. See this fiddle where the following #name does not override the css of div#name.
I would guess that including the element name in your id selector would actually be slower – browsers typically hash elements with id attributes for quicker element look up. Adding in the element name would add an extra step that could potentially slow it down.
One reason you might want to use element name with id is if you need to create a stronger selector. For example you have a base stylesheet with:
#titlebar {
background-color: #fafafa;
}
But, on a few pages, you include another stylesheet with some styles that are unique to those pages. If you wanted to override the style in the base stylesheet, you could beef up your selector:
div#titlebar {
background-color: #ffff00;
}
This selector is more specific (has a higher specificity), so it will overwrite the base style.
Another reason you would want to use element name with id would be if different pages use a different element for the same id. Eg, using a span instead of a link when there is no appropriate link:
a#productId {
color: #0000ff;
}
span#productId {
color: #cccccc;
}
Using #name only:
Well the first obvious advantage would be that a person editing the HTML (template or whatever) wouldn't break CSS without knowing it by changing an element.
With all of the new HTML5 elements, element names have become a lot more interchangeable for the purpose of semantics alone (for example, changing a <div> to be a more semantic <header> or <section>).
Using div#name:
You said "with the reasoning that it's slightly faster". Without some hard facts from the rendering engine developers themselves, I would hesitate to even make this assumption.
First of all, the engine is likely to store a hash table of elements by ID. That would mean that creating a more specific identifier is not likely to have any speed increase.
Second, and more importantly, such implementation details are going to vary browser to browser and could change at any time, so even if you had hard data, you probably shouldn't let it factor into your development.
I use the div#name because the code is more readable in the CSS file.
I also structure my CSS like this:
ul
{
margin: 0;
padding: 0;
}
ul.Home
{
padding: 10px 0;
}
ul#Nav
{
padding: 0 10px;
}
So I'm starting generic and then becoming more specific later on.
It just makes sense to me.
Linking div name: http://jsfiddle.net/wWUU7/1/
CSS:
<style>
div[name=DIVNAME]{
color:green;
cursor:default;
font-weight:bold;
}
div[name=DIVNAME]:hover{
color:blue;
cursor:default;
font-weight:bold;
}
</style>
HTML:
<div name="DIVNAME">Hover This!</div>
List of Css selectors:
http://www.w3schools.com/cssref/css_selectors.asp
Is it recommended to combine equal declarations in CSS in order to reduce the filesize and avoiding duplications?
For Example:
#topbar,#searchbox.focus,#usermenu li:hover a,#cart-flyout-table tbody td,.btn_remove:hover,#heading-warenkorb a:hover,.button:hover span,.input-text:focus,#pages li a:hover,select:focus,.picture-overview li:hover,#category-sub li a:hover {background-color:#e3eed3}
Is it recommended to do this for some other Properties which are used very often like float,text-align or padding for example?
The Code would getting harder to read and edit but if this will be done only for the most common properties I would accept it. What's about the performance at the rendering? Would it make my website faster or slower?
The answer is: varies.
In general, I would only recommend on doing that when the elements in question are similar in content or in area. I'll explain.
let's say you have a sidebar, and that sidebar has several headlines in it, which you wish to have similar stylings. That's perfectly acceptable to use aside h1, aside h2, aside h3 { font-weight: normal; color: blue; }.
However, to use it the way you described, for a 100 different elements on different parts of the page, then I won't recommend it.
I would avoid the type of CSS styling you mentioned.
It makes your stylesheets much harder to read and update.
Instead, I would group styles according to sections of the page
nav, header, content, etc.
or by actions
form, call to actions, etc.
or a combo of both.
If you see some duplication within those categories, then combining would be fine.
Otherwise, for example, if you want to update one a, you may need to look in four or more different places (for link, active, visited, and hover).
i can't see any problem in combining declaration.
Yet, if you want to apply the same style to your whole page, you'd better considering calling body { } or * { }.
Details to choose between these two are described here: difference between body and * in css
You may also consider using classes or css inheritance to avoid so many combination