4. Styling
The teaching of Less and CSS is outside the scope of this academy. However, there are a few important points to keep in mind. Most of the concepts I explain here apply not only to WEM widgets but also to web development in general.
Global Space
When you publish or preview a WEM application, the Less styles from all the widgets are combined into a single CSS file. This CSS file is then included in the design template. This presents a significant issue: all the CSS exists in a global space. I briefly discussed this in previous chapters. As we learned, if you are not careful, you could inadvertently overwrite the styles of other widgets or any HTML element, for that matter! For example:
In this case, both Bob and Jane have created a card widget using the class name "card." Even if Jane's widget is not used on a page, if Bob's widget is included, it may appear to have a strange yellow background. This can lead to confusion and blame for issues that are not actually related to Bob's widget. It is advisable to make class names more unique. You can add prefixes to the class names, such as your initials, your company name, or both, like this:
CSS Variables
When WEM supported widgets, it included Less by default. Less is powerful because it supports variables, which makes styling more organized and easier to maintain. Nowadays, CSS variables are supported in all major browsers and offer even greater capabilities. You can alter the value of a CSS variable in real time, creating new opportunities for styling your widgets. You can still use Less variables as a base. For example, consider the following Less code:
However, if you save this code, you will encounter an error message indicating a syntax error on the line setting the border
property.
Escape Syntax
What is happening here? This is because Less has its own syntax and attempts to parse the CSS value as a Less expression. We can resolve this issue by using the escape syntax ~"value"
. If we modify the line as follows:
This change makes the code valid. While it may not be ideal, it is better than nothing.
Embedding Resources
You may be wondering how to embed a resource in Less. The short answer is that you cannot do it directly. The following code, which uses a made-up WEM style syntax, will not work:
To achieve this, you need to revert to using the <style>
tag or apply it via JavaScript.
Was this helpful?