Recently, there has been a lot of comparison between CSS and JavaScript, with arguing about the application of these technologies to solve specific problems. The controversy is getting hotter as great new CSS features emerge that make it easier to solve a lot of problems while leaving JavaScript behind.
6 Best CSS Features & Techniques You Can Use Instead of Javascript
CSS and JavaScript work well together, each of these technologies has its own strengths, but we are confident that the more CSS is used to control the appearance and behavior of interfaces, the more fault-tolerant and more reliable web applications will be. It is because:
- CSS, by its nature, is rejection-resistant technology. This means that when a CSS parser encounters a property that it doesn't understand, it simply ignores it and moves on. In other words, using CSS, the programmer applies the styles and expects them to work.
- JavaScript is not a fault-tolerant technology. A single syntax error in the JS code can break the entire application. That is, when managing the styling of sites using JS, it is absolutely necessary to check the functionality of the corresponding structures.
There are many other considerations to take into account when answering the question of when to use CSS over JS.
CSS gives us new ways to design fantastic solutions that are much simpler than the corresponding JS solutions, and are easier to create. This refers to many of the features of CSS: transitions, custom properties, animations, filters, math.
In this post, we'll cover some of the cool features of CSS (some of which are very recent) that you may not know about yet. Namely, we will talk about smooth scrolling, about the position: sticky property, and about other features that previously required writing a lot of tricky JS code lines.
1. Smooth scrolling
Previously, to equip a page with smooth scrolling, it was required to use several lines of JS code. And now this task can be solved exclusively by means of CSS. Well, isn't it wonderful? You can now take advantage of smooth scrolling by using the scroll-behavior CSS property.
This is how it looks:
html {
scroll-behavior: smooth;
}
2. Pinning elements
Anchoring elements is one of our favorite CSS features. The point is that the corresponding elements do not disappear from the viewport when scrolling through the pages. Now you don't need to resort to offsetTo and window.scrollY in JS to pin elements to pages. These days, you can simply use the position: sticky CSS property:
header {
position: sticky;
top: 0;
}
In order to use this property correctly, you need to take into account its specific effect on elements. When applied, the structure of the HTML page plays a certain role. By the way, sometimes the reason why the position: sticky CSS property does not work lies in the fact that this effect has not been taken into account
Let's take a look at the following HTML code:
<main class="container">
<nav class="nav">
<ul>
<li>Home</li>
<li>About</li>
<li>Contact</li>
</ul>
</nav>
<div class="main-content">Main Content</div>
<footer class="footer">Footer</footer>
</main>
The menu (the nav element from this example) can only be pinned to the area that its parent element overlaps (main in our example). As a result, when using the position: sticky property, there are two main classes of elements:
- Dockable element: This is the element to which we apply the position: sticky property (nav in our case). This element will move within the parent element until it reaches the given position. For example, it could be top: 0px.
- Dockable element container: This is the HTML element that contains the dockable element. This is the area within which the docked item can move. This "container" defines the boundaries within which the dockable item can exist.
Using this feature can significantly improve the usability of the site. This is especially true for those projects whose users have to scroll through the pages frequently.
This feature has almost 100% browser support.
3. Cropping text
CSS gives us two wonderful properties: text-overflow and line-clamp. They allow you to trim text, carefully handle words, and at the same time save us from the need to use JavaScript or some other complex methods to solve such problems. Both properties are not new, but extremely useful.
Let's take a closer look at the text-overflow and line-clamp properties.
The text-overflow property
This property controls how text is displayed in situations where it should be truncated if it does not fit on one line. An example of such a situation is shown in the above figure, in the header of the card. Here you can use the construction text-overflow: ellipsis, which will lead to the fact that a Unicode character (...) is added to the end of the trimmed text.
For the text-overflow: ellipsis property to do its job, you must also use the white-space: nowrap and overflow: hidden properties.
.card-title {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
This feature is almost fully supported in all modern browsers.
Line-clamp property
This property comes to our aid in cases where we need to work not with a single-line, but with multi-line text (an example of such a text is the contents of the card from the above figure). Although this is a part of the CSS Overflow Module Level 3 standard, which now has the status of "Working Draft", this feature is already supported by about 95% of browsers, albeit with the -webkit- prefix. Before using it, it is important to take into account that it does not provide the ability to control the number of characters displayed. But it's incredibly useful anyway.
To use it, we need to use the old flexbox implementation by applying the display: -webkit-box and -webkit-box-orient: vertical properties. This is what it looks like:
.card-title {
overflow: hidden;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 3;
}
4. Custom CSS Properties: CSS Variables
In the JavaScript world, CSS preprocessors (like Sass, Less, and Stylus) are very useful and popular technologies. Preprocessors extend the capabilities of CSS, allowing you to use, for example, variables and functions. But modern web designers have access to powerful standard CSS features known as custom CSS properties or CSS variables.
CSS Variables help keep apps consistent and help implement DRY. They facilitate the development and maintenance of application themes. These capabilities are one of the main reasons for the success of preprocessors.
Using standard CSS features means you no longer need preprocessors to create variables. Variables, like other standard CSS features we love, work in a cascading fashion.
It is very easy to create CSS variables. Namely, to declare a variable, it is enough to put two dashes (-) in front of its name. After that, where the value of the variable is needed, the function var () is called, passing it the previously created variable as an argument. As you can see, everything is very simple.
:root {
--base: #ffc600;
--spacing: 10px;
--blur: 10px;
}
img {
padding: var(--spacing);
background: var(--base);
webkit-filter: blur(var(--blur));
filter: blur(var(--blur));
}
.hl {
color: var(--base);
}
CSS Variables can be manipulated from JavaScript.
5. Providing support for the dark mode
Since Apple introduced the dark mode for macOS last year, and because CSS gave us the ability to detect uses of this theme using media query, many large web projects (like Twitter and Google Maps) have adopted this theme.
The dark mode is not just a way to decorate web pages. It can really help some people surf the Internet.
Here are some quotes that illustrate its usefulness.
And then there are people who, for objective reasons, need dark mode. They use this mode as one of the tools for people with disabilities. For example, we are talking about people with low vision.
Thomas Steiner, Customer Solutions Engineer, Google, Germany.
Molly has Usher syndrome. Because of this, she does not hear anything, and the field of view of one of her eyes is limited to 5 degrees. (…) Viewing pages in dark mode will be within her power. This mode can be useful for other people as well, expanding the possibilities of using the Internet for those who have a headache, or for those who have to sit at a computer in a poorly lit room. If, when developing something, focus only on some special users, it will be useful not only for them.
Charles Reynolds, Designer, UK Government.
In addition, from the material by Thomas Steiner, you can learn that the use of the dark mode helps to save energy: “(...) as you know, using the dark mode on AMOLED displays can save a lot of energy. Android research, targeting popular Google apps like YouTube, has shown that energy savings can be as high as 60% in some cases. ”
A new CSS feature that lets us know if a user has a dark mode enabled is the prefers-color-scheme media function. It is already compatible with Chrome, Firefox, Safari and Opera.
Combining this with CSS Variables means that it is not hard for a web developer to make it easy for its visitors to take advantage of the dynamic light and dark modes.
:root {
--color: #222;
--background: #eee;
--text: 'default';
}
body {
color: var(--color);
background: var(--background);
}
body:after {
content: var(--text);
display: block
text-align: center;
font-size: 3rem;
}
@media (prefers-color-scheme: light) {
:root {
--color: #222;
--background: #eee;
--text: 'light';
}
}
@media (prefers-color-scheme: dark) {
:root {
--color: #eee;
--background: #222;
--text: 'dark';
}
}
6. The @supports directive
For a long time, web developers have had to resort to third-party solutions (like the Modernizr JS tool) to find out if certain CSS features are supported by the current browser. For example, by configuring the -webkit-line-clamp element property, you can check if the property is supported in the browser, and if not, you can use some fallback.
After the @supports directive appeared in CSS, it became possible to check the capabilities of browsers directly from the CSS code.
The @supports directive is very similar to media queries. It supports various combinations of expressions built with the conditional operators AND, OR, and NOT:
@supports (-webkit-line-clamp: 2) {
.el {
...
}
}
This checks if the browser supports the -webkit-line-clamp property. If so, that is, if the condition is true, the style declared inside the @supports directive will be applied.
All modern browsers support this feature.
Conclusion
In this article, we've covered some of the useful features of CSS. If you can do something without using JS, but only using CSS, then do so.
The modern world of the frontend is rapidly changing, we constantly have new opportunities at our disposal that help us do our business faster and better. Experimenting with CSS and learning new things is not only very rewarding, but also extremely interesting. Why not try out the new things you have learned about today?
Enjoy successful development! :)