[Front-end dictionary] 9 CSS tips to improve happiness

Preface

In this article, I will introduce 9 tips to make your CSS more concise and elegant. These skills are often used by young students, and they find it very efficient and practical, so I have this article.

9 CSS tips

I hereby declare that the CSS mentioned here does not only include CSS, but also includes CSS preprocessors (Less Sass, etc.). I hope that you will not be entangled in this.

The text begins now.

1. Try to use padding instead of margin

When we restore the design draft, padding and margin are two commonly used attributes, but we know that the margins of two adjacent boxes belonging to the same BFC will overlap, so if the margins are used too frequently, the vertical of the box The distances may overlap.

Another problem is the bug that the margin-top value of the first child element will be added to the parent element (the margin-bottom of the last child element also has a similar problem). Is anyone here asking why?

The reason is:

the expression collapsing margins means that adjoining margins (no non-empty content, padding or border areas or clearance separate them) of two or more boxes (which may be next to one another or nested) combine to form a single margin.

The translation is:

The margins of all adjacent two or more box elements will be merged into a shared margin. Adjacent is defined as: same level or nested box elements, and there is no non-empty content, Padding or Border separation between them.

As for the reason for merging, I personally think that this is similar to the safety distance for queuing withdrawals. The safety distance between people is 1m. If the safety distance is not merged, will the distance between people be 2m when we line up? Up. Of course, this is probably not the reason.

So we can use padding in the first element instead of margin. Of course, sometimes the use of padding cannot meet the needs, then you can also make a fuss about the "non-empty content" condition. That is, add a pseudo element to the parent element.

So we must pay attention to collapsing margins when using margins.

2. position:fixed downgrade issue

I don’t know if you ever encountered the ceiling effect or used the position:fixed attribute. In fact, if transform is used in its parent element, the effect of fixed will be downgraded to absolute.

solution:

Since it will be downgraded to an absolute effect, how can we solve this problem? We will consider under what circumstances fixed and absolute performance effects will be the same.

That is, when the height of the direct parent element using fixed is the same as the height of the screen, the performance effects of fixed and absolute will be the same.

If the element in the immediate parent is scrolling, add overflow-y:auto.

3. Use px | em | rem |% and other units reasonably

There are many distance units in CSS, such as px | em | rem | %, as well as units such as vh | vw in CSS3.

So how should we use it in the project? We don't need to consider this complexity on the PC side, so here we mainly talk about the use of these units on the mobile side.

Base unit px

px is the first unit we came into contact with, but our frequency of use is not very high under the requirements of mobile end adaptation; I have summarized the following use cases:

Relatively small pattern

For example, we need to draw a circle with r being 5px. If we use rem as the unit, we will soon find that the pattern on some models is not round and will appear elliptical. This is due to the loss of precision when converting rem to px.

So at this time we need to use px and dpr to achieve:

// less 

/*@size 建议取双数*/

.circle(@size, @backgroundColor) {  

    width: @size;

    height: @size;

    background-color: @backgroundColor;

    [data-dpr="1"] & {

        width: @size * 0.5;

        height: @size * 0.5;

    }

    [data-dpr="3"] & {

        width: @size * 1.5;

        height: @size * 1.5;

    }

}

1px thin line problem

I will talk about this issue in a separate section below, so I won’t go into it here.

Font size (basically rem is used as the unit)

In general, I also use rem as the unit of font size, because the precision is lost, I think it is within an acceptable range.

Relative unit rem

Rem is a new relative unit (root em) added by CSS3, which is the value of the font size relative to the HTML root element.

Rem should be the most widely used unit for adaptive.

Relative unit em

em is also a relative unit, but it is relative to the font size of the current element.

line-height

It is generally recommended to use em in line-height. Because when you need to adjust the font size, you only need to modify the value of font-size, and the line-height has been set to the relative line height.

Indent the first line by two characters

I will also use this unit when there is a need for first line indentation.

text-indent: 2em

Viewport unit vw | vh

vw: 1vw = 视口宽度的 1%
vh: 1vh = 视口高度的 1%

We know that the flexible layout designed in rem units requires a script to be loaded in the head to monitor resolution changes to dynamically change the font size of the root element, so that CSS and JS are coupled together.

So is there a solution to this coupling problem?

答案就是视口单位 vw | vh。

The following is the usage plan given by the predecessors:

$vm_fontsize: 75;

@function rem($px) {

     @return ($px / $vm_fontsize ) * 1rem;

}

$vm_design: 750;

html {

    font-size: ($vm_fontsize / ($vm_design / 2)) * 100vw; 

    @media screen and (max-width: 320px) {

        font-size: 64px;

    }

    @media screen and (min-width: 540px) {

        font-size: 108px;

    }

}

// body 也增加最大最小宽度限制,避免默认100%宽度的 block 元素跟随 body 而过大过小

body {

    max-width: 540px;

    min-width: 320px;

}

4. Reasonable use of variables

Generally, a certain type of text (element) in the design draft uses the same font size, color, line height and other style attributes, so we don’t have to write these values ​​every time, because when the UI updates the design, you need to change There are many places. We can store these reused values ​​in variables.

Sass and Less are slightly different:

// sass

$direction: left;

// less

@direction: left;

Of course, there are variables in CSS natively, and the usage rules are as follows:

变量定义的语法是: --; // *为变量名称。
变量使用的语法是:var();
  1. Both the definition and use of variables can only be in the declaration block {}

  2. CSS variable character limits are: [0-9], [a-zA-Z], _, -, Chinese and Korean, etc.
    :root {

        --blue_color: #3388ff;

        --main_bgcolor: #fafafa;

        --font_size_12: 12px;

        --font_size_14: 14px;

        --color: 20px;

    }

    .div1{

        background-color: var(--main_bgcolor);

        font-size: var(--font_size_12);

    }

5. Use Mixin to classify repeating patterns

Like repeated variables, repeated patterns can also be classified. I think one of the excellent codes must be the reusability of the code.

When we wrote CSS before, we also put some reusable code in a class, which did achieve a certain reusability, but the final effect may be to put a lot of classes in an element, as shown in the following figure:

[Front-end dictionary] 9 CSS tips to improve happiness

In this way, the next person who takes over will inevitably be a little confused, and this will make the style more and more difficult to modify.

At this time, mixin (can be understood as the class in class) can play its role.

This is a style of descriptive text:

.font-description {

    .font-des-style(24px,#fff,1.5em);

    .line-camp(2);

}

// less

/* 多行显示 */

.line-camp( @clamp:2 ) {

    text-overflow: -o-ellipsis-lastline;

    overflow: hidden;

    text-overflow: ellipsis;

    display: -webkit-box;

    -webkit-line-clamp: @clamp;

    -webkit-box-orient: vertical; 

}

.font-des-style( @fontSize, @color, @lineHeight, @textAlign:left ) {

    font-size: @fontSize;

    color: @color;

    line-height: @lineHeight;

    text-align: @textAlign;

}

This is just a simple example. We can put reusable styles in the mixin, so that the person who takes over the project only needs to be familiar with the mixin.less you wrote to start iterating requirements.

6. 1px scheme

The front end that has done the mobile terminal must definitely not avoid dealing with the 1px thin line problem. The reason for this problem is that the UI requires more and more page aesthetics (don't tell me this is a retina screen problem).

As far as Xiaosheng knows, there seems to be no solution with particularly good compatibility. Here I just provide two relatively good solutions.

Use pseudo-class + transform

.border_bottom { 

    overflow: hidden; 

    position: relative; 

    border: none!important; 

}

.border_bottom:after { 

    content: ".";

    position: absolute; 

    left: 0; 

    bottom: 0; 

    width: 100%; 

    height: 1px; 

    background-color: #d4d6d7; 

    -webkit-transform-origin: 0 0;  

    transform-origin: 0 0; 

    -webkit-transform: scaleY(0.5);

    transform: scaleY(0.5);

}

Of course, in some models with lower versions, this solution will also have compatibility problems such as uneven thickness and thin lines disappearing and breaking. But now it's 2019, and models with lower versions are almost eliminated.

Use box-shadow simulation

.border_bottom {

  box-shadow: inset 0px -1px 1px -1px #d4d6d7;

}

This scheme can basically meet all scenarios, but there is a drawback that the color will become lighter.

7. Inherit box-sizing from html elements

In most cases, we are setting the border and padding of the element and do not want to change the width and height of the element. At this time, we can set box-sizing: border-box; for the element.

I don't want to rewrite it every time, but hope it is inherited, then we can use the following code:

html {

  box-sizing: border-box;

}

*, *:before, *:after {

  box-sizing: inherit;

}

The advantage of this is that it will not overwrite the box-sizing value of other components, and there is no need to set box-sizing: border-box; repeatedly for each element.

8. Inline key CSS for the first screen

There is an important indicator in performance optimization-First Effective Draw (FMP), which refers to the time when the primary content of the page appears on the screen. This indicator affects the time users need to wait before seeing the page, and the inline Critical CSS (or Critical CSS) can give users a better psychological expectation.

As shown:

[Front-end dictionary] 9 CSS tips to improve happiness
We know that inline CSS can make the browser start page rendering time earlier, that is, it can be rendered after the HTML download is complete.

Since it is the inline key CSS, it means that we will only write a small part of the CSS code directly into the HTML. As for which CSS to inline, you can use Critical.

9. The text exceeds the omission, and the text is aligned at both ends

We often encounter such needs in our needs, and we provide solutions directly here.
Beyond omission

.line-camp( @clamp:2 ) {

    text-overflow: -o-ellipsis-lastline;

    overflow: hidden;

    text-overflow: ellipsis;

    display: -webkit-box;

    -webkit-line-clamp: @clamp;

    -webkit-box-orient: vertical; 

}

Problems encountered:

-webkit-box-orient:vertical This code will be deleted when using webpack to package, the reason is the problem of optimize-css-assets-webpack-plugin.

solution:

You can use the following wording:

.line-camp( @clamp:2 ) {

    text-overflow: -o-ellipsis-lastline;

    overflow: hidden;

    text-overflow: ellipsis;

    display: -webkit-box;

    -webkit-line-clamp: @clamp;

    /*! autoprefixer: off */

    -webkit-box-orient: vertical;

    /* autoprefixer: on */

}

[Front-end dictionary] 9 CSS tips to improve happiness

Justified

// html

<div>姓名</div>

<div>手机号码</div>

<div>账号</div>

<div>密码</div>

// css

div {

    margin: 10px 0; 

    width: 100px;

    border: 1px solid red;

    text-align-last: justify;

}

The effect is as follows:
[Front-end dictionary] 9 CSS tips to improve happiness

Front-end dictionary series

The "Front-end Dictionary" series will continue to be updated. In each issue, I will talk about a knowledge point that appears frequently. I hope that you will be able to find any imprecise or wrong places in the text during the reading process. I will be very grateful; if you can gain something through this series, I will also be very happy.

If you think my article is well written, you can follow my WeChat public account, which will spoiler you in advance.
[Front-end dictionary] 9 CSS tips to improve happiness
You can also add my WeChat wqhhsd, welcome to communicate.

Next preview

In the next few articles I will introduce Vue related

Guess you like

Origin blog.51cto.com/15077552/2596474