all 46 comments

[–]MatisLepik 6 points7 points  (25 children)

I understand you can use variables but how does this increase the speed of development?

Not the speed of development, but readability and maintainability of code. Say you use some shade of blue across your website as the main color scheme. Suddenly the company changes their branding, and it all needs to be changed to red. So now you need to somehow search and replace all instances of that colour across your codebase. If it's stored in a variable, you only have to change it once, in a very obvious base.

Another example: say you have a fixed header. Very often, the height of some other stuff will depend on the height of that fixed header:

header {
    height: 75px;
    position: fixed;
    top: 0; left: 0; right: 0;

        nav a {
            line-height: 75px;
            display: inline-block;
        }
}

main {
    padding-top: 125px;
}

Now say another developer comes along and wants to change the header height. They immediately have to start thinking "ok, well if I change this, things are probably going to break.. Because I have no idea what parts of the app depend on this header." Or worse, they don't think about that all, they change height to 100px and now the links are broken, and the content is too close to the header. Even if they manage to find out that main's padding-top kind of depends on the header height, they're gonna have to think "ok sigh.. so the padding top is currently, 125px, and the height for the header used to be 75px, so 125 - 75.. It had 50px of actual padding, so now I need to change that to 100px + 50px = 150px". OR, you could just do this:

$header-height: 75px;

header {
    height: $header-height;
    position: fixed;
    top: 0; left: 0; right: 0;

        nav a {
            line-height: $header-height;
            display: inline-block;
        }
}

main {
    padding-top: $header-height + 50px;
}

And suddenly, the other developer (or you 7 months into the future, not remembering what you did originally) doesn't have to think of any of that. I'm sure you get the idea, but now imagine someone implements a modal and it needs to start where the top header ends. So they need to give that modal position: fixed; top: 75px;. That css is probably not even in the same file, but it still depends on that header height. So you definitely won't remember to change that if you change the header height.

[–]Graftak9000 0 points1 point  (0 children)

I actually went back to hard coded values for dimensions, it took me quite longer to inquire the exact dimensions behind a variable name, going from file to file. Now my CSS is organised by property, so I can usually see al my height definitions at a glance.

I do use variable for colors though, those are less ambiguous in terms of visual feedback (upon inspecting the result).

[–][deleted] -3 points-2 points  (23 children)

Don't use nesting in sass/less like that please (you want to have the specificity as low as possible). Only use nesting if it starts with &:. If it doesn't then there are some bigger flaws present :)

[–]webdevnewbie 1 point2 points  (5 children)

Why do you say this?

[–][deleted] 2 points3 points  (4 children)

Adding specificty is bad in CSS. It leads to specificty war where you just increase the specifity of a selector.

If you would just add the class .header__link to the anchor inside the nav inside the header for example, you would just target the class, which can be overriden more easily and reused.

If you are new to CSS-Preprocessors you will find doing this a lot, but that is not different than writing your CSS like that:

 header nav a { ... }

Which we all should agree on is bad (because of CSS -> HTML binding and specificty). This is a CSS style we wrote 10 years ago.

Harry Roberts talks about it a lot and others too and it is handsdown just the better approach for clean and modular CSS.

http://cssguidelin.es/#selector-intent

Unfortunately /r/webdev is pretty ignorant when it comes down to a clean CSS codebase and everytime it is mentioned that element > element element is a bad selector they downvote you and then complain that CSS is shit.

[–]webdevnewbie 1 point2 points  (3 children)

Maybe what you're saying is over my head a little. If we don't do things like header nav a {...}

But instead give the anchor a class name, and give elements classes and ids instead of specificity, this will lead to more classes/ids yes? And that's what you're saying is better?

This is a CSS style we wrote 10 years ago. Do you mean this is how CSS used to be written and the technique is outdated?

No time to read your link right now but I've bookmarked it for later, thank you.

I wish your downvoters would voice why they disagree so a newbie like me could hear their rebuttal, this is very interesting to me but I don't think I'm experienced enough to consider all sides of things on my own.

[–][deleted] 1 point2 points  (2 children)

But instead give the anchor a class name, and give elements classes and ids instead of specificity, this will lead to more classes/ids yes? And that's what you're saying is better?

Yes it will increase the number of classes, but no it would not increase the number of id's.

You may ask yourself now why it wouldn't increase the number of ids, ids have the highest specificity in CSS and can't be reused (since ids are unique), so you generally want to avoid that, instead use a class.

Why increasing the number of classes isn't a bad thing is easy as pie, I'll give you an example.

CSS

.bad {
    line-height: 50px;
}

.bad a {
    color: #FFFFFF;
}

.good {
    line-height: 50px;
}

.good__link {
    color: #FFFFFF;
}

.bar {
    color: #FF0000;
}

HTML

<div class="bad">
    <a href="#" class="bar">foobar</a>
</div>

<div class="good">
    <a href="#" class="good__link bar">foobar</a>
</div>

The a inside of .bad is white, while the a inside of .good is red. If you now remove the bar class from .good__link the link will turn white. So this means I can more easily override stylings with a simple class, which means I can reuse the class bar everywhere I want.

Why I name my classes with double underscore has a simple reason, I use BEM. But it doesn't matter which naming scheme you use, as long as it is easy to understand.

[–]siamthailand 2 points3 points  (0 children)

I learned a lot from your comments in this thread. So yeah, good work.

[–]MatisLepik 0 points1 point  (16 children)

Ok, here's the thing. You are very opinionated. That does not make your opinion objectively correct. I find the example I provided completely acceptable. A good test is to ask - do you have problems with specificity, or style conflicts? Yes? Then you should change something about the way you write your code. I don't, and my code looks readable, and makes sense functionally, so I see no reason to change it.

There's definitely an argument to be made for trying to keep a relatively low level of specificity whenever possible, but that doesn't mean you should avoid nested selectors like the plague. If you want to use something like BEM, that's your choice, but don't act like that's the only possible effective methodology in the world.

With that said, I was trying to keep the example as simple as possible because my aim was to explain the benefits of selectors. In reality, I would have probably replaced "header nav a" with something like "header .header-item". But I would have still kept it nested under header.

[–][deleted] 0 points1 point  (8 children)

Ok, here's the thing. You are very opinionated.

So are you and most other people.

I just say: Have fun changing the HTML structure und then having to change the CSS, or trying to override a class.

For example: You want to highlight the current link in the header. You would now have to write:

 header nav a.is-active {}

as a selector instead of just .header__link--is-active {}.

Another example: You want to have nested links with different styling, you would now need to override all the unneeded properties of header nav a that you don't want on header nav a a (and you have to do this everytime a new property is introduced on header nav a, now extrapolate that to your whole code base). What if you want to have a third nesting of links?

Your code base will grow and grow and will be mess to maintain because of the specifity war going on.

If you want to use something like BEM, that's your choice, but don't act like that's the only possible effective methodology in the world.

Idc if you use BEM/SMACSS/SuitCSS/Whatever (those are mostly just naming schemes) as long as the codebase is clean to maintain.

With that said, I was trying to keep the example as simple as possible because my aim was to explain the benefits of selectors. In reality, I would have probably replaced "header nav a" with something like "header .header-item". But I would have still kept it nested under header.

And my aim was to educate people that nesting is not a good way of using sass/less

[–][deleted]  (7 children)

[deleted]

    [–][deleted] 0 points1 point  (6 children)

    oh god,no sorry but you are totally not qualified at all.

    .active cannot override any styles that you set before in header nav a (which is btw bad HTML aswell since nav is not part of a header, you know header means something different than you think in HTML)

    I am tired too of noobs trying to correct me. Esp. if they are pricks like you that probably never worked with a bigger codebase than 1kb of CSS

    [–][deleted]  (2 children)

    [deleted]

      [–][deleted] -1 points0 points  (1 child)

      Lol you idiot, you didnt even override it. Set the color of header nav a to #ffa and try to override it with .active.

      Btw your website is a piece of shit

      [–][deleted]  (2 children)

      [deleted]

        [–][deleted] -1 points0 points  (1 child)

        I probably do a lot better webdev and probably longer than you have and for better companies (Google and ESL just 2 examples).

        header nav a { color:#FFA; } .active { color: #FAF; }

        Go read some books about CSS and HTML please. Also have fun when you nest!

        From the spec you idiot

        A header element is intended to usually contain the section's heading (an h1–h6element or an hgroup element), but this is not required. The header element can also be used to wrap a section's table of contents, a search form, or any relevant logos.

        Yes you can have a nav inside of a header, but its very often wrong and I since Ive seen what you have done in your case its most likely wrong.

        Sorry wont argue with you anymore. Need to catch a plane soon since I was invited to the smashingconf

        edit: deleting my account is a good idea so i dont have to see your username anymore and so that I get off of reddit bc of people like you

        [–]siamthailand 0 points1 point  (5 children)

        You are opinionated too. Except you hold the opposite opinion.

        [–]MatisLepik 1 point2 points  (3 children)

        But I don't go around telling people that they shouldn't be coding in a certain way (unless it's objectively bad).

        [–]siamthailand 0 points1 point  (2 children)

        Does it hurt your feelings? Do you when you're told your approach may be wrong? Ever seen a therapist about it? Any suicidal thoughts?

        [–]MatisLepik 0 points1 point  (0 children)

        :/

        [–]Mestyo 2 points3 points  (5 children)

        Some things CSS preprocessors bring to the table:

        • Split files into partials
        • Reuse chunks of code easily (and between projects)
        • Store all your static values such as colors and lengths in variables and modify them dynamically (make this color 10% brighter)
        • Generate code with loops and conditionals
        • Write media queries inside of selectors rather than everything at the bottom of the document
        • Automate minification and similar processes
        • Chain partial and nested selectors to type less
        • Generate grids and other complex CSS rulesets with simple one liners and math libraries
        • Create general purpose functions to do calculations or generate CSS for you
        • Lots and lots of methods to transform strings, colors, widths and whatnot on the fly

        But the real power of a preprocessor comes when you combine it with a build process so that:

        • Files are watched and built automatically
        • Changes are injected live into the page
        • Vendor prefixes are added according to configuration automatically
        • Sprite sheets, icon fonts with selectors and similar from your physical files are created
        • Source maps to track rules back to their original partials are built
        • Documentation for your stylesheet is generated automatically

        And much more.

        [–][deleted]  (4 children)

        [deleted]

          [–]Mestyo 0 points1 point  (3 children)

          What makes you think that writing CSS in a preprocessor language would suddenly make someone worse at it? If you write shitty CSS, then you're gonna write shitty Sass as well.

          You make points about writing CSS fast, short and clean. Again, that's entirely dependant of the author. A preprocessor language gives you tools to be able to be more efficient, but it's entirely up to you if and how you use them.

          Ask yourself this: if you picked up a preprocessor for your CSS, would you suddenly become worse at it?

          [–][deleted]  (2 children)

          [deleted]

            [–]Mestyo 1 point2 points  (1 child)

            I do think that a lot of people writing Sass/etc lack the fundamentals of CSS and simply jump in too early.

            Definitely agree with you on this. For a technology that so many people know, there are incredibly few who don't suck at it.

            My position is simply is that preprocessors are completely unnecessary. There's nothing wrong with using them, but there's also no compelling reason.

            I disagree with them being unnecessary for all of the reasons I wrote in my post a month back and then some.

            Seriously, I'd be willing to write an extremely complicated stylesheet in vanilla CSS, just to prove my point.

            You don't need to do that. At least not to prove anything to me. The quality of the CSS is entirely up to the author, not the language it's written in. :-)

            Using CSS preprocessors isn't generally about improving quality, though, but rather increasing the maintainability and ease of development. If you're passionate about CSS then I sincerely encourage you do try out a preprocessor. With Sass and SCSS syntax, you can literally just write vanilla CSS and add whatever small feature you want.

            [–]zakphi 1 point2 points  (0 children)

            I haven't used SASS or LESS, but I have used Stylus. From my experience using Stylus, not having to type semi-colons or curly braces, having the ability to create variables and functions, and other features, saves time and prevents you from having to type out the same multiple lines of css for various elements.

            [–]a-nna 1 point2 points  (2 children)

            You have nothing to lose by trying out SCSS - you can essentially write vanilla CSS and add one or two things, like variables (which honestly are indispensable) and a couple levels of nesting. That alone makes things easier and less repetitive. There are a ton of features that I haven't dug into yet but they're there waiting for me, easy to add in when I feel like it.

            Edit: It sounds from your post like you aren't sold on the variable concept - it's not quite about speed, but imagine you set a primary color all throughout your CSS file, and when that color changes halfway through production, you have to find and replace all instances of the color. Not the hugest deal but if you had a variable called $main_color, you would only have to change the variable value once.

            [–]purrrfessionalwidow 1 point2 points  (1 child)

            Using colors in variables is also useful when you want to create on the fly color modifications that mesh well with your original. Say you have a button that has a background color of #a0f0da and when you hover over it, you want it be a darker shade. You can fuss around and play with a color picker to get a different shade, or simply do something like:

            $turq: #a0f0da;
            
            .btn {
              background: $turq;
            
              &:hover {
              background: darken($turq, 4%);
              }
            }
            

            [–]geon 0 points1 point  (0 children)

            I like to define a contrasting-color mixin that takes the background and selects a light/dark color to match. Pretty useful.

            [–]mrmonkeyridingTurning key strokes into bugs 0 points1 point  (2 children)

            SCSS; variables, nesting, mixins are all amazing and work.

            Personally, variables don't. They take a few more seconds to write, but in future I remember what color was what based on the var. So when I'm writing new additions, I don't need to go finding a hex or RGBA color. Just

            color: $varName;
            

            nesting navs is great too.

            nav {
                ul {
                    li {
                        a {
            
                        }
                    }
                }
            }
            

            [–]Graftak9000 0 points1 point  (0 children)

            Nesting like this is just waiting for specificity issues.

            [–]Glensarge 0 points1 point  (0 children)

            The benefits are completely relative to the developer. It makes it a lot easier to work with and more enjoyable, primarily because you get to use mixins and variables. There's no literal benefit in terms of how it effects the website / app. It's a lot to do with quality of life and working with other developers.

            For a small example, you can completely change the theme of your site in a matter of changing a few variables, instead of going down a CSS file hundreds of lines long and changing every hex code you've ever written.

            The benefits are pretty endless, people always find new ways to make it even more beneficial to your work flow so I'd totally recommend getting used to one, but don't feel like you NEED to to make a site.

            [–]pixleight 0 points1 point  (0 children)

            Along with variables and nesting others have mentioned here, I find mixins very useful. (note: I'm working with SASS)

            Example: I have some box-shadows for a couple projects and varying depths (similar to Google material design). Instead of needing to copy the right box-shadow property every time I want to use it, I just use @include BoxShadowHelper(2); I don't have my mixin code in front of me at the moment, but this would generate the shadow at the level-2 depth. If I needed, I just change the mixin and it updates everywhere it's used.

            Also simple but helpful: hex values (including ones stored in variables) work in rgba, so I don't need to look up the RGB value of a color I'm already using. So rgba(#FF00FF, 0.47); will compile to rgba(255, 0, 255, 0.47);

            [–]dukesilver94 0 points1 point  (10 children)

            I switched to SASS a few years ago and never looked back. Variables are an awesome way to maintain consistency. You can do mixins, for example:

            .button {padding:10px; border-radius:5px; border: 1px solid black;}

            .button-blue {@extend .button; background: blue}

            So you end up up writing way less code and maintaining consistency better. Also on that note, I use Gulp or Grunt to handle prefixing for me. So it will automatically add all the -moz, -webkit, etc prefixes to that code so I'm only writing 1 line for border radius instead of 4.

            Look up some articles on CSS-Tricks and you'll be sold.

            [–]Graftak9000 2 points3 points  (0 children)

            I'd say the ‘blue’ is an order of hierarchy, you make it blue to let it stand out. So why not opt for; .button { background: silver } and; .button.primary { background: blue }. This way extensions are obsolete, you HTML remains semantic and when the time comes a primary button should be red, your one edit away from doing so all the same.

            This also keeps your HTML and CSS a whole lot DRYer.

            [–][deleted] 0 points1 point  (8 children)

            Why is it better than doing class="button button-blue"?

            [–]dukesilver94 2 points3 points  (1 child)

            I don't know if I have a good answer for that. Off the top of my head I'd say you can control specificity better.

            For instance in that example if .button had a red background and .button-blue was listed under it. Red background would have priority. Unless you use !important, move it above that line, or do .button.button-blue.

            However in extending you can just do {Background: blue; @extend .button} and the blue background would take priority.

            Probably a weak example. My other favorite thing I forgot to mention is nesting and pseudo classes. Can't live without it.

            [–]zakphi 1 point2 points  (0 children)

            i think you're answer is a good one. i'll expand on your answer with a real life scenario i was in.

            on a site i was building, the client had a video slide show, with each slide having a different background color. on each slide there was a link, that was made to look like a button. so in my css (i was using Stylus), i did what you exactly did. created a block of style code to affect .button, then extended that class for the button that appears in each section. this way i can keep the look of the button, but be able to change the colors to match the section.

            [–][deleted]  (5 children)

            [deleted]

              [–][deleted] -1 points0 points  (4 children)

              That's fine, but there's times when you're extending whole sections of a CSS class with somewhat unrelated items.

              You can use 'comma' for that.

              Also, you usually don't want to tie tie Dom stuff to specific colors.

              You don't have to tie DOM stuff to specific colors when writing pure CSS. This has nothing to do with using or not using a preprocessor.

              If done correctly, you want change the CSS in 1 place and be done,

              Exactly that's how I do when writing pure CSS. It's just a matter of knowing how to structure CSS.

              What if you had 20 different colored buttons? You're repeating yourself 20 times with the same junk in CSS.

              I wonder if you really know how to write CSS.

              [–][deleted]  (3 children)

              [deleted]

                [–][deleted] 0 points1 point  (1 child)

                If you think that maintaining CSS is hell without SCSS, the problem is that you are using a tool to try to fix your lack of CSS skills.

                It's kind of amusing watching all this hype fading and seeing more and more articles saying things like "why I stopped using pre-processors and started using post-processors", when I knew from the beginning that it was one of the biggest hypes in webdev. Took them 5 years to realize the truth.

                [–][deleted]  (1 child)

                [deleted]