Auto-Generating Z-Indexes with SASS

z-index

Z-index management is one of the most useful things that SASS gives us. We no-longer need to fiddle with numbers, and the order is presented in a direct, visual way. Introducing the mixin:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@mixin u-z-index
{
    $z-list:
        '.w-home-banner-arrows'
        '.w-home-banner-pager'
        '.w-home-banner-ad'
        '.w-carousel-previous'
        '.w-carousel-next'
        '.w-bottom-bar-categories-box'
        '.w-bottom-bar-categories-box-sub-category'
        '.w-middle-bar-classifications-box'
        '.w-middle-bar-search-toggle[aria-pressed=true]::after'
        '.w-middle-bar-search-box'
    ;
    $me: "#{&}";
    $z-val: index($z-list, $me);
    z-index: $z-val * 10 + 100;
}

This is how it’s used:

1
2
3
4
5
.w-bottom-bar-categories-box
{
    @include u-z-index;
     
}

Managing Z-indexes is now as simple as adding the mixin to your element, then adding the selector to the list within the mixin. You can change the z-index order by moving the selector lines around in the list. The final z-index will be a result of its index within the list, times 10, plus 100. I start my lists at 110 as there are some javascript libraries that auto-generate z-indexes between 1 and 100. You can remove that part if you don’t need it.

This functionality is achieved by others in different ways, you should check them out too and decide what would work best for your project. Remember, keep it simple unless you can justify the need for added complexity.

Other examples:

https://www.sitepoint.com/better-solution-managing-z-index-sass/

https://www.smashingmagazine.com/2014/06/sassy-z-index-management-for-complex-layouts/

https://jonsuh.com/blog/organizing-z-index-with-sass/

Some of these other examples add z-index ‘categories’ and assign each element to a category. I prefer to do without categories and ensure that each element has a different z-index. These techniques are a great example of how to use new technology to improve the quality of code.

CSS Preprocessors – Write LESS and put some SASS into your styling

sass_0

As a website styler, it can get quite frustrating in this world of CSS, having to endlessly replicate code lines just to target another selector below the one you are styling, it can add up to literally thousands of lines of code, unnecessary code as well which you will eventually have to sift through just to find that line height that seemed like a good idea to set at the time…

Enter the CSS Preprocessor, this little tool will change your styling world forever. Just a precursor though, whilst I will be explaining LESS in this blog post, you can apply the same theory to almost any CSS Preprocessor.

I was forced to use LESS about a year or two ago when looking into using the Bootstrap framework, at first I hated it, it seemed so overly unnecessary, and it didn’t seem to help me at all.

After getting frustrated and just dumping my normal CSS within the LESS files, I realised there must be a reason that such a juggernaut like Bootstrap uses such a tool like this. So I did some homework.

If you are looking for some good tutorials then the best place to start is usually the site where the code comes from. So I made my way to http://lesscss.org and started to read up.

It’s really quite simple, each level you want to select can be nested and styled within itself.

Take this code snippet for example.

body {
background: url(‘/some/awesome/picture.jpg’);
padding: 10px 20px;
}
body #header {
background: #000;
color: #fff;
}
body #header p {
font-size: 14px;
color: #666;
}
body #header p span {
background: #000;
color: #fff;
}

Quite cumbersome when you have to write out the same classes again and again just to target another selector… If this were done with LESS you can squeeze it into the following.

body {
background: url(‘/some/awesome/picture.jpg’);
padding: 10px 20px;
#header {
background: #000;
color: #fff;
p {
font-size: 14px;
color: #666;
span {
background: #000;
color: #fff;
}
}
}
}

At first this might seem pointless, you aren’t actually saving any lines of code, but it’s the fact that you don’t have to keep retyping (or copying and pasting) the same selectors again and again.

Also this way you can group your styling and have much cleaner and leaner code.

This is just the tip of the iceberg with LESS though, there is MUCH more that can be done with it. The point of LESS is to use LESS code.

Mixins as they are known in LESS language are snippets of code that you can re-cycle, so you don’t have to keep writing out the same thing time and time again and they also mean you will never have to use that hacky method of search and replace EVER (seriously I mean it).

Take the example below:

.button {
color: #fff;
background: #ff000;
}
.header {
color: #fff;
background: #ff000;
}
.page-title {
color: #fff;
background: #ff000;
}
.brand-highlight {
color: #fff;
background: #ff000;
}

This snippet is one that is used a lot when you are dealing with a business brand colour, for this example the brand colour is red. Now let’s say you wanted to re-use this in an entire new site, but the new brand colour was blue… with CSS you would whip out the old search and replace and hope to god that:

  1. All the spacing was the same…
  2. The exact same hex code was used every single time…
  3. If there were any variations, again, the same hex code was used
  4. There was only 1 style sheet… otherwise you are in for trouble

These are just the things that spring to mind, and I can guarantee that every time you do this, there will be some stupid variation that a designer put in, like a drop shadow that is an alpha with some transparency or a tint colour or SOMETHING like that.

Again this is where LESS will save you literally HOURS of time. The mixin is set once and then is reused throughout the project and can be manipulated without ever having to change the original colour.

See the snippet above, used below with LESS

@brand-primary: #ff000;
.button {
color: #fff;
background: @brand-primary;
}
.header {
color: #fff;
background: @brand-primary;
}
.page-title {
color: #fff;
background: @brand-primary;
}
.brand-highlight {
color: #fff;
background: @brand-primary;
}

To make this even more advanced you can use:

.brand-highlight {
color: #fff;
background: @brand-primary;
text-shadow: darken(@brand-primary, 80%);
}

So now when you change the mixin colour at the start of the code, it will flow through beautifully and change all the styling with one fell swoop (take that Search and replace!)

To touch on the above code as well, LESS also allows you to have the ability to apply mathematical functions to any style so you can have pixel point accuracy, most designers use percentage for opacity or colour changes (like a highlight or hover colour) and this way you can apply it in the same way, so when the client says “just a little lighter” rather than whipping out your hex colour palette, just change the percentage to match and it’s all done for you.

There is A LOT more you can do with these processors, but I thought I would share some easy to explain features which have really changed the way I style.

GOTCHAS

A complex program needs memory

LESS is no exception, you will need your own development server, and you don’t want to be coding in LESS on a live site. It uses resources which converting all the coding to CSS and it is not shy about gobbling them all up. But with that, it will make sure you use proper web development practices, develop on a dev server, save all your changes, and then put them live.

Learning LESS is hard at first

It can be difficult if like me, you can be styling for well over 10 years… I was set in my ways, but over the last 2 years, I have relearnt and been able to take advantage of LESS. It’s not ALWAYS the right time to use LESS If you have a site that you don’t really have access to obtain a dev copy of, or it is quite a simple design, sometimes a CSS prepocessor might not be the right option, so you need to pick and choose your battles. Have fun! Links to some CSS Preprocessors:

  1. Sass – http://sass-lang.com/
  2. Less.js – http://lesscss.org/
  3. Stylus – http://learnboost.github.io/stylus/
  4. CSS-Crush – http://the-echoplex.net/csscrush/
  5. Myth – http://www.myth.io/
  6. Rework – https://github.com/reworkcss/rework

OVER ENGINEERING

over

The days of pure HTML, CSS and Javascript are over. Now we must learn CSS pre-processors and frameworks, multiple Javascript libraries (usually based on jQuery) HTML templating engines based in Javascript, task runners such as grunt and gulp, etc. With all of these tools available, and becoming an ‘industry standard’, it’s easy to misuse them and make a real mess of your website coding.

The reality is, you don’t need any add-on technologies. You can always create websites with highly organised, easily maintainable code, even when using the base technologies.

Modern web development often involves over-engineering. By this, I mean that too much time is spent on setting things up, writing and configuring tools and finding ‘smart’ ways of doing things instead of just doing what needs to be done in a logical manner.

CSS Preprocessors

Nesting

We all know the rule that selectors shouldn’t be nested more than 4 levels deep. However, I disagree with this, as I find that nesting selectors at all will make the code less readable. It’s easy to scan code in a vertical manner, but when my eyes need to also scan horizontally, it makes scanning much less efficient.

If I am looking through a style sheet and I find a class nested a few levels deep, I need to know the parent selectors to understand how the class is being applied. I need to scroll up to see the parent selector, then scroll up again to see its parent selector, then again. It’s not immediately obvious or straight-forward how it will be applied, I need to scan entire blocks of code to understand one line. It’s not a problem if the blocks are small, but there are usually quite a few child selectors under the parent block.

What I often see is a top-level class being used like a namespace. While it may seem neat to organise code this way, it takes more time and effort to understand it. It doesn’t add anything to the code organisation that you couldn’t do with a few line-breaks or comments. The only benefit is reduction of selector repetition. If organising CSS like programming code was that important, we would have adopted JSS instead of CSS.

I prefer to only use nesting for states and, sometimes, pseudo elements.

Media Queries

Another issue I sometimes come across is the use of multiple repeated media queries. Should each selector have its own media query? What about when they’re nested? It can become a bit messy and hard to see the big picture if so much functionality is separated into multiple super small media queries.

I prefer to use a set of media queries per ‘module’ or ‘feature’, so I don’t have a million media queries and yet I also don’t have one big monolithic set of media queries at the end of the file.

Useless complexity

One of the worst examples of investing time into making something that is often unnecessary, useless or even detrimental, would be the idea of wrapping media queries in pre-processor functions or mixins. I can understand the desire to use this when you have a lot of very complex media queries, used often. However, in most cases it’s just not necessary. You will see a line of code like this:

1
@include respond-to($medium) { }

What exactly does this do? It’s media query related, but you will need to go looking for the definition of $medium to know if it is just a pixel value, a query or a key relating to a keymap. Either way, you need to find the query text, the associated pixel values, how to use this function and what options are already available.

You will need to read and understand the definition of the function to see how it implements these variables. Does it use min-width or max-width as a default? Does it have default functionality?

What benefits does this function hold over a set of variables? You don’t need to type the word ‘@media’ anymore, instead you need to write ‘respond-to’. This is replacing a universally understood piece of fundamental CSS with a lesser-known custom implementation.

It’s always interesting to see what you can do with the tools available and how far you can go. However, we are replacing a straight forward set of readable statements with a slightly more cryptic line of code that needs to be investigated and understood by a programmer.

The benefit of this technique relies largely on how complex your media queries are, and how often your media queries are used. For sites that use simple media queries, storing the pixel value in a variable will be just as effective. For slightly more complex queries, you can store the entire query in a variable.

The creator of this technique warns his readers about finding a balance and picking the right tool for the job. I’ve seen this technique used in a way that is detrimental to the project many times.

Before using this technique, you need to consider if it’s the right thing to use for your project. Consider your development environment, project size, tooling and style of coding. Don’t just use this because it’s ‘good / standard practice’. Use it only if it suits your project.

Javascript

Libraries

When you want to read a book, you go to the library and borrow one. However, common practice with Javascript is to borrow the whole library just to read one book. Often, libraries like Bootstrap are included and used just for one feature. One feature that you could write in three lines of code. It’s important to justify the inclusion of an entire library before you do so.

Insane code

A previous company that I used to work for, had outsourced a project to an overseas company. One feature of the website was a little call to action button that would stick to the top right of the screen when the user scrolled past a certain point.

The developers had implemented this by using a collision detection system about a page long. It detected when any part of the element collided with the banner above it, so they knew when to remove the fixed position if the user was scrolling upwards. It was probably ripped from some game engine. I’m surprised they didn’t go one further and program some sort of self-learning AI to achieve the same task.

How many lines of code would it take you to implement that functionality?

Lack of programming knowledge

1
2
3
4
5
6
If (I == true)
 {
     I = false
 } else if (I == false) {
     I = true
 }

Actual code. From a teacher in a web development course. This was back in 2008. It’s memorable, but not in a good way.

This is not as common nowadays as most people know about the ‘not’ operator, but I have seen people implement code to replicate the functionality of the ‘modulus’ operator.

It’s important to know the features of the languages you use.

Conclusion

There are many motivations to complicate your code. To improve maintainability, improve functionality, boredom, being a smartypants, to annoy people for fun etc. However, keep in mind that in a year’s time, you may be the one working with your own code, cursing the developer who made this mess, only to find out that it was you who screwed you over. Yes, I’ve been in that situation, which is how I know. It’s also why I do things simpler and, for the lack of a better term, slightly more old-school than most people when possible.

Heart of a Layout: CSS Display Properties

Before starting any design, you need work on building blocks of that design, with a strong foundation, you always try new techniques, and creating something awesome that you’re proud of. So for gaining this proud, you should be aware with basics. I know you are an expert and Writing a good CSS is no different for you and it all starts with understanding what you’re working with, before you write a single line of CSS. In a design we have many blocks with different elements, like paragraph with full width, images block with different width and height, and many more. Web browsers that render to a screen defines their own style to govern the default layout of HTML elements. This CSS are called the user agent CSS, and are responsible for a mostly consistent experience across the different Web browsers.

For every HTML element that the WHATWG define some CSS. This CSS is not much different to the CSS we will write, and also can override. WHATWG defines display: block;  for body Tag automatically.

But we can change it in many ways, Like- display: none; OR anything else.

 Let’s understand the display properties: Experiments says <DIV> and <P> behave like same.

 :- Block -:

 p {

display:block;

margin: 0;

}

 

div{

display:block;

}

 

Here both div and p tags are assigned display: block;. Only one thing is different, <p> has some assigned margin. display: block; makes block-level elements, which have the following properties:

  • Bu Default – Occupy full width of a container.
  • Respect top / bottom padding and margin.

Given properties are very useful.

:- Inline -:

display: inline; Very Important style. You can get this property in anchors, spans, strongs, and a slew of other mostly typographical elements by default. Display: Inline; elements allow us to stack HTML tags next to each other, without affecting the layout of pages and these elements ignore most vertical and horizontal layouts. Also ignore the height, top and bottom padding and margin.

inline occupy only the width of their content block – as if they are shrink-wrapping around their content.

:- inline-block -:

display: inline-block; This property gives you the best of inline and block-level elements in one.

Block can be assigned explicit widths They respect vertical margins and padding values.

inline-block will stack with other non-full width elements, until content width reaches the full width of the content block, at which point it will always occupy its own line. Inline elements, in contrast, will always wrap to new lines with adjacent non-full width HTML elements.

 

:- Vertical Alignment -:

Other very helpful attribute of inline-block elements is that they also respect the vertical-align property for differing vertical Ys. inline-block elements respect vertical properties while Block elements don’t respect any vertical-alignment properties and inline elements respect vertical alignment.

 

When To Use What?

Simple way is to start your design by asking some yourself:

Screen Shot 2016-06-05 at 3.16.21 PM

Must Try these display properties carefully.