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.
Related
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.
One feature I really love with LESS is nested rules. It makes the stylesheet much cleaner that way and you can find an element very quickly.
I was wondering if there's an option when compiling to optimize selectors. For example...
#global {
/* Styles here maybe */
.container {
/* Styles here maybe */
#sidebar {
/* Styles here maybe */
.title {
font-weight: bold;
}
}
}
}
will be compiled to #global .container #sidebar .title { font-weight: bold; }.
But the first two selectors are useless, since #sidebar should be unique in my page.
Is there a way to ask LESS to compile this to #sidebar .title { font-weight: bold; } instead?
Your assumption is wrong that multiple IDs in CSS are redundant. Imagine, as an example, a site where the CMS generates the page type into the output, like that it's the contact page:
<body id="contact">
<section id="content">Blah</section>
</body>
According to your logic, the following piece of CSS would be a candidate for 'optimization':
#contact #content {
background:red;
}
Now however, your home page has <body id="home"> of course in this imaginary CMS. And suddenly the content of your homepage has a red background because you decided to erroneously optimize that #contact selector out of the CSS, while it most certainly shouldn't have a red background according to this rule.
So no, LESS cannot do this because it would break code. If you don't want the selectors, don't use them and don't put them in your code.
Other answers, including the accepted one, have explained convincingly why LESS cannot simplify your nested selectors in the way you want.
Actually, SASS has the ability to do this:
#global {
.container {
#at-root #sidebar {
.title {
font-weight: bold;
The #at-root directive essentially ignores all the higher nesting selectors. I don't know if LESS has something similar. The above compiles into simply
#sidebar {
.title {
font-weight: bold;
But there is a deeper issue here, starting with the fact that you "love" nested rules in LESS. Stop loving them quite so much. I don't know about you, but most people love nested rules because they think it's cool to exactly mimic the hierarchical structure of their HTML. The SASS docs even claim this as a benefit:
Sass will let you nest your CSS selectors in a way that follows the same visual hierarchy of your HTML.
So people with HTML such as
<div class="foo">
<ul>
<li class="item">
write LESS like
.foo {
ul {
li.item {
This is a horrible, horrible idea, It makes the structure of CSS completely dependent on the structure of the HTML. If you change one nesting level in the HTML, your CSS breaks. Often this approach is combined with a lot of rules defined against tag names such as ul instead of class names, which aggravates the dependency, so changing the ul to ol in the HTML breaks the rules again. Or it's combined with rules based on Bootstrap classes such as col-md-6, so if you ever change that to col-md-4 things break again.
CSS rules should be orthogonal to the HTML. They represent a different dimension. They represent styling concepts which are applied selectively throughout and across the HTML.
I am guessing that you wrote
#global {
.container {
#sidebar {
.title {
font-weight: bold;
because you are adopting this mistaken idea of mirroring the HTML structure in your LESS. Then, you notice that this compiles down to having selectors which contain multiple IDs, which you imagine must be inefficient (although, actually, the degree of inefficiency is minimal). You yourself are writing extraneous nesting levels in your LESS, then complaining that they may be slowing down performance!
Worse, you've hard-wired assumptions about the HTML structure into your CSS. It's of no consequence that the sidebar happens to fall inside a .container which is inside a global element. So don't write them. Perhaps at some point you decide to change the container class to container-fluid. Boom, instantly your CSS breaks. What is the point of conditionalizing the fact that the title should be bold on it being contained with a container class, which in any case is a layout-related class that has (or should have) nothing to do with styling? If you're going to duplicate your HTML structure in your CSS using preprocessor nesting, just go back to writing inline styles. At least that way you'll only have one file to change when you change your HTML around.
When designing CSS, you should think just as hard about the design of the rules as you do about the design of classes and methods when writing JS. In this case, you need to ask yourself, "What characterizes the situation where I want some title to be bold? What drives that? What is the nature of boldness? What am I indicating by boldness? What is the semantic notion indicated by boldness?"
Let's say that you want all titles to be bold. Then you simply say that:
.title { font-weight: bold }
Let's say that you want a title to be bold only when it's in the sidebar. Then you simply say that:
#sidebar .title { font-weight: bold; }
My suggestion here is to go cold turkey. Stop using nesting during a withdrawal period. Write rules with the minimum number of selector components. Refactor your classes to have semantic names (such as title-emphasis). Once you're "sober", you can go back to cautiously using LESS's nesting capability when it is useful, such as perhaps for hover:
#boo {
color: red;
&:hover {
color: blue;
}
}
This is actually useful and saves you from writing #boo twice, and groups the rules in an easy-to-understand way.
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 mostly a backend programmer, and am relatively new to CSS. So far, I hate it. My biggest complain is that is incredibly redundant and difficult to produce readable code.
Many times I need to apply styling to different but similar elements. However, I find it incredibly challenging to produce elegant code to do that.
The most simple way to do things in CSS seems to be to give an ID to everything and use custom code for every single element in the page, or classes when there are repeated elements with. However, this still leaves a lot of repeated code, like when I have two elements that are almost exactly alike, but have one or two different attributes, like width, background color, color or float side.
My current solution is defining many atomic classes, like
.bgRed { background-color: red; }
.bgBlue { background-color: blue; }
.fontCenter { text-align:center; }
.left { float: left; }
and so on, and applying multiple classes to an element, like this:
<span class='bgRed left' >My text</span>
But that's still very short of decent. Some attributes, like width and height, are usually strongly tied to it's elements, so I can't create an atomic class for it, and end up resorting to using it's ID.
Finally, my question: Why doesn't CSS support some kind function-like structure? Would a feature like this be useful in CSS? Is CSS badly designed or I just don't know how to use it properly? Why was CSS designed the way it is?
How I imagined functions in css would work:
Defining a css function:
_sidebar(float_side, color, width){
float: float_side;
backgroud-color: color;
width: width:
height: 200px;
color: #FE02A5
list-style: none;
display: table;
}
And applying:
<div cssfunc='sidebar(left, #FF0000, 150px)' >
<ul>
<li>Item One</li>
<li>Item Two</li>
</ul>
</div>
Bonus question: How do you maintain you CSS code readable and organized, with minimal code repetition?
This is not the intended usage pattern for CSS. A general clue is if you have specific formatting words like colors or alignments in your class name, you're not following the "spirit" of CSS.
The intention for CSS classes is to use semantic categories for class names. For example instead of having a class named bgRed, use one called warning. The difference might be subtle in some cases, but the difference in philosophy usually helps maintenance. Instead of combining "literal" css rules at the element level, you'd combine more meaningful semantic ones like class="sidebar warning".
With that said, some people still find the lack of reusability of formatting between CSS rules cumbersome. There are fixes for that as well. The best solution is to use a CSS pre-processor like LESS or SASS. These languages compile into CSS, but support things like mixins and variables that function very much like the css enhancement you have in mind.
HTML defines what to show, CSS defines how to show it. If you use classes like "bgRed" or "left", you are doing this old way.
CSS doesn't define support functions, but LESS does. Imagine this:
.sidebar(#side, #color, #width) {
float: #side;
backgroud-color: #color;
width: #width:
height: 200px;
color: #FE02A5
list-style: none;
display: table;
}
.sidebar-important {
.sidebar(left, red, 100px);
}
.sidebar-misc {
.sidebar(right, blue, 50px);
color: grey; // overwrites .sidebar function
}
Then in HTML:
<div class="sidebar-important">Important news</div>
<div class="sidebar-misc">Something else</div>
This way, you can easily change values in LESS file, compile it to CSS and you won't need to change it in HTML.
Bonus answer:
LESS.
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’ve been trying to find out various ways to manage my CSS files which become bigger and bigger as time progresses. This has a few reasons: creating websites using responsive design, plugins that require additional styling or just page-specific styling for a single element.
There are a few techniques I’m already using, like:
Creating a table of contents
Separating code into named sections (to be referred in the table of contents)
Name-spacing the elements (.home-gallery, .home-gallery-image, .home-gallery-link etc.)
Yet there’s still the issue of how to lay down the properties for each element.
Putting everything in a single line significantly decreases the readability. On the other hand, putting each and every property in a single line makes my scrollbar go sit under a shower and cry.
I’m currently experimenting with some different forms, and here’s what I came up with:
Sorting and organizing properties according to their types
Using tabulation/spacing to create a sort of table-look (captions on the left: elements; contents on the right: properties)
In an example it looks as follows:
#content-wrapper {
position: relative; top: 0; left: 0;
width: 100%; height: 200px;
color: #333; background: #fff;
}
For now it seems to me, like the only compromise between having to scroll endlessly/searching for a piece of code and making it less-readable.
So my question is: What CSS writing techniques do you use that allow for good readability and further development?
1) I define style in the order of elements in the HTML
eg: html{ } head{ } body{ } likewise in the order. So while scrolling it will be easy to locate an element for me.
2) Writing styles in the order of screen width, if media query is included. From higher screen width to lower one. Which helps me to find the styles written for media elements easily. There also I follow the first point.
3) Format styles. It is almost like you did.
4) Keeping a documentation.
sample below:
/* indented multi-selectors */
#content-wrapper
, #content-wrapper > something else {
/* alphabetic listing of properties, organizing attributes in blocks */
background-color: #fff;
border-left-width: 2px; /* column layout with blockwise different positioning */
/* separation of blocks */
color: #333;
height: 200px;
left: 0;
position: relative;
top: 0;
width: 100%;
}
probably more important than formatting and organization of individual properties is a clean structure based on conspiring classes and proper documentation, especially of the rules' sequencing (it certainly has been in my projects. often the other way round ... ;-).
imho a decent folding editor sufficiently mitigates the need of frequent scrolling. and large screens, of course.
When I first started writing CSS, I was writing it in an expanded form
div.class {
margin: 10px 5px 3px;
border: 1px solid #333;
font-weight: bold;
}
.class .subclass {
text-align:right;
}
but now I find myself writing css like this: (Example from code I'm actually writing now)
.object1 {}
.scrollButton{width:44px;height:135px;}
.scrollButton img {padding:51px 0 0 23px;}
.object2 {width:165px;height:94px;margin:15px 0 0 23px;padding:15px 0 0 10px;background:#fff;}
.featuredObject .symbol{line-height:30px; padding-top:6px;}
.featuredObject .value {width:90px;}
.featuredObject .valueChange {padding:5px 0 0 0;}
.featuredObject img {position:absolute;margin:32px 0 0 107px;}
and I'm beginning to worry because a lot of the time I see the first form done in examples online, while I find the second form a lot easier for me to work with. It has a lower vertical height, so I can see all the classes at a glance with less scrolling, the tabulation of the hierarchy seems more apparent, and it looks more like code I'd write with javascript or html. Is this a valid way of doing code, or to keep with standards when putting it online should I use the vertical form instead?
Well, here is what say the most :)
summary:
css-tricks.com ran a poll. By a margin of roughly 3 to 1, most people preferred multi-line over single line css styles.
I personally prefer the first style. I like things that are easy to read and I don't mind scrolling. The dense nature of the second style slows down my reading, my ability to pick out the items that I'm interested in.
There certainly are trade offs to be considered with CSS due to the file size. CSS can be compressed. I find the size of CSS files to be the least of my worries with the sites I've built so far.
Ultimately, the important thing is that whichever style you choose to use is to be consistent. That consistency will make your life simpler when you have to update your CSS or when another developer has to update your CSS.
Indicating the hierarchy using indentation is not a bad idea. However, you should be careful that you don't fool yourself. In your example, you may be assuming that .scrollButton is always within .object1. But CSS doesn't obey that rule. If you used a .scrollButton class outside of .object1, it would still get the styles.
I dont know about you but I like the vertical mode during dev as it is far more easier to read for me.
However, in prod, you wanna compress your css to reduce payload and hence, the second style makes sense. Mostly, you would be using some CSS compressor to do this.
i like to write css in multi line. because this is easier to write and read. we can find error as early as possible and a look of view is nice with indentation . mostly when a designer work with css and gave to developer to develop site than developer can understand easily.
so i think multi line css is better way to work.
I personally find both of your examples hard to read, especially the second one.
Multi-line is easier to follow, and indentation can be misleading as CSS is not necessarily applied in that way. Your indentation may lead you to believe it is.
I prefer the basic tried and true method of multi-line, with reasonable/logical order:
div.class
{
margin: 10px 5px 3px;
border: 1px solid #333;
font-weight: bold;
}
.class
{
text-align: center;
margin-left: 10px;
}
.class .subclass
{
text-align:right;
}
Takes up a little more space and requires a little scrolling to take in, but is easy to follow. Those worried about optimization can always use CSS shrinking tools for production CSS files.
In the end as long as you are very consistent with your work and across a team (if applicable) then no answer is more correct.
I prefer the second style, but be aware that it's a style. In the same way that some people prefer
function (arg)
{
body();
}
to
function(arg){
body();
}
I don't get it, myself. The argument is "it's easier to read", and my response is consistently "... for you". As a note, I get the feeling that this is why so many examples use the more-whitespace version; it has the reputation (if not confirmed property) of being easier to read.
Pick the one you like and stick with it. If you have a team to cooperate with, try to get to consensus, or barring that, write some auto-formatting scripts and stay out of each other's way. It's not like it's terribly difficult to mechanically transform one into the other.
The style you write in is your choice(I prefer multi line) but as Rajat said you want to remove any extra whitespace after dev. Anytime you can reduce file size and payload you are doing your site and your visitors a favor.
I think it also depends on your editor. I use multi line formatting and condense every definition with Vim's folding (I set up folding marks to be { and }) so I get one tag/class/id per line, expandable when needed.
Using comments to identify "sections" I get a very clean look with minimal vertical scroll while maintaining the readability of multi line on expanded definitions.
I just want to point out that Textmate has an option that allows you to easily switch between these two styles by selecting an area and pressing Ctrl-Q/Ctrl-Alt-Q to expand/collapse. As a consequence I have come to find that I prefer my CSS collapsed unless I am writing or deep debugging a specific section. But, with the ability to easily switch between he two I see that both ways are useful for different circumstances.
I prefer multiline right up until we deploy. At that point I want it minified.
Perhaps, when you have multiple selectors and one rule, like this:
#header li a, #header li span {
display:inline-block;
}
So, I prefer to do:
#header li a,
#header li span {
display:inline-block;
}
I've always liked this style:
#something1 {
color : #ffffff;
background : #000000;
}
#something2 {
color : #000000;
background : #ffffff;
}
But yo answer your question: As long as it functions the same way, there is no "proper" or "best" way to format your code. Use a style your comfortable with.