Some Mindset when CSS code

Tram Ho

CSS is sometimes very simple, sometimes complicated, or even looks outdated.

Why does CSS cause so many different emotions to developers? The possible reason is that we need certain mindset to write better CSS.

Perhaps we already have coding mindset in general, but the nature of CSS makes it particularly difficult to capture. Programming languages ​​often operate in a controlled environment. On the other hand, CSS works in a place that can never be completely controlled. Actually, the mindset for writing CSS often comes after everything is almost done. It is not simply about grasping the techniques, but also the idea behind the language.

The following are some Mindset should keep in mind when CSS code

Everything (should) be rectangular

This is obvious, because the model box concept is the first thing people learn about CSS. However, sometimes we forget it. Imagine each DOM element being a box whether it’s inline, block, or flex. Wrap them in a rectangle and make sure they work well in different scenes.

To test, we can open devtools, hover over the elements to visually see the boundaries of each element.

“Cascade” is “you”

Cascade means “cascade”, simply understanding that our CSS code will go from top to bottom and higher priority. Although there are some reasons to avoid Cascade, but does not mean that Cascade in CSS is bad. In fact, when used correctly, it is for our code to be more awesome.

The important thing is that we must distinguish the styles of the global range and which styles are the best. It helps the default styles to be retransmitted and we do not need to repeat those declarations again.

The less the better, the more necessary it is

Fewer attributes mean less inheritance, less trouble. However, think about the meaning of our selector writing, do just that, avoid unnecessary or irrelevant styles that the selector brings.

Know the Shorthands (short spelling)

Some properties in CSS can be written in short syntax. This helps to declare related properties on one line. Although this is convenient, keep in mind that when using shorthand, the default values ​​are also declared when not explicitly set. When writing:

Related properties will be set:

It’s better to point out that we want to use background-color

Try to keep things flexible

CSS handles a large number of unspecified variables: screen size, dynamic content, … If the hard styles of attributes, the likelihood of our results will be wrong compared to the design.

Try to think of a ratio, rather than a number.

Remember that content can always be changed

Break down the components, think of the larger element as a box containing small elements, and make sure these elements are not stuck anywhere.

Cases often need to be predicted: very long strings / contain special characters; images may be missing or “odd” aspect ratio; The screen can be very narrow or extremely wide.

Share the news now

Source : Viblo