“This is my fourth day of participating in the First Challenge 2022. For more details: First Challenge 2022.”

In daily work sometimes encounter a lot of styles or functions need to use JS Settings, but if you know enough about CSS, part of the content can actually only use CSS to achieve;

So HERE I will list my personal use of high frequency of small skills, I hope I can insist on maintaining this article, later to learn new good CSS use, and then update into this article;

If someone shares some ideas in the comments section, I’ll look them up and add them.

Calc function

I usually use calc when I’m dealing with a fixed size on one side of a page, because either the top or the sides need a fixed size, so the width of the other side can be calculated directly using calC;

Left {width: 100px; height: 100vh; } .right { width: calc(100% - 100px); height: 100vh; }Copy the code

Of course, calc is more than that. The Calse function can perform simple computations in CSS (addition, subtraction, multiplication and division). It can not only compute certain values, but also CSS variables.

// In the following example, 'box-1' is always half the width of 'box'. width: var(--myWidth); } .box-1 { width: calc(--myWidth / 2); height: 100vh; }Copy the code

Another advantage of this is that if the project uses a lib-flexible dependency to convert px, it will not have to recalculate in JS to dynamically modify the size.

Long text beyond automatically converts to…

In projects, I often encounter the problem of displaying long text, and in the beginning, I always judge the string length first, then cut the string according to the appropriate length, and then add the ‘… ‘, this is not only troublesome, if the width changes, the length to be cut must also change;

Until I found text-overflow, setting this property automatically converts text overflow inside block elements to ‘… ‘

<p class="txt">aaaaaaaaaaaa</p>

<style>
.txt {
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
Copy the code

CSS selectors

Some of my favorites are:

  • :nth-child(1) – First finds all the siblings of the current element, and then matches the number of elements based on the value you entered
  • :last-child – The last element in the current element collection
  • :first-child – The first element in the current element collection
  • :not()

The first three are easy to understand and should be used a lot in your daily life. The last one is not(), which I discovered recently. Most selectors do assignments, while :not() does not, and it can operate on selectors and elements;

// Set the background color of all elements that are not <p> elements :not(p) {color:#ff0000; } p:not(:last-child) {color: #f40; color: #f40; }Copy the code