10 CSS Pro Tips you need to know about
10 CSS pro tips: In our recent poll with over 75,000 responses, CSS topped the list as the most painful technology web developers have to work with. They say it’s broken, chaotic, and too damn hard. There’s even a conspiracy that it’s bad by design to protect the app stores. But, we think CSS is awesome it’s definitely bloated and difficult to learn comprehensively, but that’s only because it’s had to evolve over the last 25 years.
Why Everyone hates CSS?
It came out at a time when Netscape was the top browser. The idea of a responsive layout was more than a decade away as more browsers hit the market. They all implemented CSS in different ways leading to code that works in one browser but not the other. It requires the developer to write a bunch of confusing vendor prefixes in your code just to make it work across all browsers. So, we totally get why you would hate CSS, but today is a therapy session where you’ll learn how to write clean CSS using modern features while avoiding the bad code that you shouldn’t have to write in 2021.
How to learn CSS
The first thing you need to know is how to learn CSS the way not to learn CSS is to use a framework like Bootstrap or tailwind. They’re sexy tools that can help you get a nice looking UI quickly. If you use something like tailwind in your project, it’s like getting married for one, you won’t learn CSS fundamentals you’ll learn tailwind, and two if you ever change your mind you’ll have to go through a very nasty divorce with Tailwind.
1. Learn CSS Box Model
10 CSS pro tips: When you learn basic CSS you’ll have more control over your code creativity and freedom. The best piece of advice that we didn’t receive until well into my web development career was to learn the CSS Box Model. When you understand it everything else in the language starts to make more sense. In Fact, it’s so easy we can just teach you the box model right now.
Think of every HTML Element as a box, inside that box you have the content which can have a width and height. You can add padding around that box to squeeze the content. You can add a border around the outside then additional invisible space around the border called a margin. Everything in CSS related to layout and position is influenced by the Box Model. If you open up Chrome Dev Tools, you can see how the Box Model is computed for any element on the page.
2. Don’t Use Chrome
10 CSS pro tips: That brings us to tip number two don’t use chrome when debugging CSS, instead check out Firefox their dev tools are generally superior, especially when it comes to CSS. If we inspect an element, we have a breakdown of the Box Model like we do in chrome, but we can also edit properties on it directly. Firefox gives you a breakdown of all the properties that are influencing the Box Model. It also provides useful annotations in the HTML like, when one element is causing another element to overflow. Firefox also provides really nice graphics for flex and grid layout.
10 CSS pro tips: Layout or the positioning of elements relative to each other has historically been one of the most challenging aspects of CSS like the age-old question of how do I center a div both horizontally and vertically. One option is to give the child absolute positioning then move it to the bottom right corner by using the top and left properties, then translate it back 50 to put it in the center that can work, but it’s incredibly unintuitive.
A much better approach with modern CSS is Flexbox which allows you to create a flexible column or row anywhere in the UI. When an element has display Flex, it also has an x and y-axis on which you can align its children the children flow one way which is known as the main axis and can be aligned in the center with the justify-content property perpendicular to that is the cross axis and we can move our element to the center with the align-items property.
Drawback of Flexbox
10 CSS pro tips: Flexbox is usually the first tool you reach for when it comes to layout. But, it does have one major drawback, if you have a big complex UI with many intersecting rows and columns, you may end up with a lot of container or wrapper elements in your HTML. These elements have no semantic meaning and are just there so your CSS code has something to attach itself to.
4. Use Grids
10 CSS pro tips: Luckily, there’s a modern CSS feature called a grid, that can obliterate much of your code. Unlike Flexbox, which only deals with individual columns and rows, Grid allows you to think about the big picture layout. If you’ve been a Web Developer for a long time, it may look familiar because it’s very similar to Table Layout. Way back in the day, it’s just much more developer-friendly, when you set an element to display a grid you can then define its children as a bunch of columns and rows. Columns have a width that can be defined with the Grid Template columns property. We have three values here, separated by spaces, which means our grid has three columns.
Notice the fr value or fractional unit which will responsibly share the available space with other columns in the grid. We can also define some rows and now every element inside the grid will be positioned automatically. The important thing to notice is the amount of HTML and CSS that we’ve eliminated compared to Flexbox Layout or god forbid Table Layout. Now, ninety percent of the time when we talk about responsive layouts we’re just talking about changing the width of something based on the available space on the device or viewport.
5. Use Min, Max and Clamp Functions
10 CSS pro tips: There are many ways you might do that. For example, you might have an article that has a preferred width of 50, but on small screens, you want to make it fixed at 200 pixels or fixed at 800 pixels on large screens. You could do that by writing media queries that will apply CSS conditionally based on the viewport size. The only problem with this is that media queries will make you want to off yourself as the project grows larger. The good news though is that you can turn the tables by using Functions like min, max, and clamp. We could refactor this code to set the width to a clamped value that has a minimum of 200 pixels a max of 600. A preferred value of 50 turnings 13 lines of code into one for a 92 code reduction.
6. Use Emoji Characters as Class Names
10 CSS pro tips: Speaking of code reduction here’s a little bonus tip in CSS we often end up with these very long hard to read class names. But, did you know that you can use emoji characters as class names instead of Flexible Container? Why not just use a flex emoji or instead of red text? Why not read lipstick? Is that a good idea? We don’t know, give it a try at your job and let us know what your boss says about it.
7. Use Aspect Ratio property
10 CSS pro tips: We have sort of a problem here. Now, this next tip is really going to blow your mind. If you’ve ever had to code a responsive image or video that maintains a certain aspect ratio, we had to do this recently on Fireship IO to embed videos with a 16×9 aspect ratio. It requires this hack where you put 56.25 paddings on the top, then gives the child absolute positioning. Today although it’s not supported everywhere. Yet, we can use the Aspect Ratio property, instead of that Padding nonsense. We can just define the aspect ratio on the video and we’re done.
8. Define CSS Custom Properties or Variables Notice
10 CSS pro tips: Eliminating CSS code is a big part of making it more enjoyable, but of equal importance is making your code more flexible. So, that refactoring is not a total nightmare. A great way to achieve that is with CSS Custom Properties or Variables Notice. How we’re using the same color value in multiple places, if we decide to change the color we need to modify every line of code, that references it. A better approach is to define a Global Variable on the root selector which can then be referenced wherever it’s needed.
Now when you decide to change it, you only have to modify one line of code. Variables cascade everything else in CSS, which means you can override them by redefining them somewhere deeper in the tree. You can also combine them to compose more complex values. For example, we might define our RGB color based on the value of three other variables. This flexibility will really change your life by allowing you to quickly swap out different themes for your website.
9. Combine Different Units
10 CSS pro tips: Now, CSS is not really a programming language in the traditional sense, but it does have the ability to run basic calculations using the calc function. It allows you to calculate a value with some basic math but the really cool thing about it is that you can combine different units like you might want to subtract 50 pixels from the current viewport width in our code. For example, we have an animation where elements drop in from the top, but we want to stagger them so they come in one after the other.
One way to achieve that is by applying a different animation-delay for every single element. But, that’s very repetitive and hard to refactor. A more sophisticated approach is to define an inline CSS variable for every item that defines its order. We can define the animation delay is a calculation of the order variable times 100 milliseconds. Now we can handle an infinite number of elements without increasing our CSS footprint, thanks to the combined powers of calc and variables.
10. CSS Counter
You can Create a Counter in your code using the counter reset property. Give it the name of anything you want. Increment it whenever the desired selector is applied. It’ll start from 0 then add 1 to every h1 element in the dom. Now you never have to worry about numbering things in your HTML and
Post CSS and Auto Prefixer
With that, you have 10 Pro CSS Tips to make your CSS code more enjoyable to work with. Remember those Browser Vendor Prefixes we mentioned earlier? Well, that stuff’s like Herpes it’s not going away. Luckily, we do have effective medications that will make it barely noticeable. A tool you should know about is Post CSS. Post CSS uses a tool called Auto Prefixer to add all the vendor prefixes automatically. In addition, it allows you to use modern CSS features even if they’re not supported on your targeted browsers. In addition, you may look into pre-processors like sas less or stylus but we’ll save those for future articles.