[Translation] finishing -> 20 make you more efficient CSS code tips

Translator: Jelly cc
Original link: tutorialzine.com/2016/08/20-...

In this article, we would like to share a summary of the major CSS website of the recommended 20 useful and practical experience with the rules of your collection. There is something for CSS beginners, there are some type of knowledge is advanced. We hope everyone can learn through this article useful to their own knowledge.

Well, we start.

1. Note that the folding Margin

Unlike most other properties, from the upper and lower vertical outer margin will exist when folded margins occur. This means that when an element is in contact with the lower edge to the upper edge of another element, only kept two margin values ​​in the larger one. E.g:

HTML

<div class="square red"></div>
<div class="square blue"></div>复制代码

CSS

.square {
    width: 80px;
    height: 80px;
}
.red {
    background-color: #F44336;
    margin-bottom: 40px;
}
.blue {
    background-color: #2196F3;
    margin-top: 30px;
}复制代码

Up and down the pitch with a red square blue box is 40px, rather than 70px. There are ways to solve the margins are many fold, for starters, the simplest is to use all the elements margin only in one direction, such as up and down from the outside we all use margin-bottom.

2. Use the flex layout

It appears flex elastic layout for a reason. Floating and inline-block can be achieved, although the layout much effect, but they are essentially a tool element layout and a block of text, rather than for the entire page. flex can easily create layouts as we expected.

flex has a group-oriented "flexible container" for a set of attributes and "flexible project" of the property, once you learn them, do any responsive layout is a piece of cake. The latest version of browser support for various types of flex is also no problem, so you should use a lot of flex layout.

.container {
    display: flex;
}复制代码

3. Reset CSS style elements

Despite the years it has been greatly improved, but the different browsers there is a big difference between the default styles for the various elements. The best way to solve this problem is to set common to all the elements at the beginning of CSS CSS Reset to reset the code, so you are not laid out any margin on the basis of inside and outside default, then the resulting effect is uniform.

The network has matured CSS code base for us to resolve the problem browser inconsistencies, such as normalize.css, minireset and ress, you can reference them in your project. If you do not want to use third-party code libraries, you can use the following style to a very basic CSS reset:

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}复制代码

The above code looks a bit overbearing, all the elements of the inner and outer margins are set to 0, while it is not the impact of these internal and external default margins, so CSS will set us back more easily. Meanwhile box-sizing: border-box is a great setting, we will immediately introduce it.

4. All elements set Border-box

Most beginners do not know this box-sizing property, but in fact it is very important. box-sizing property has two values:

  • content-box (default) - When we set the width or height of an element, it is to set the size of its contents. All the padding and border values ​​are not included. For example, a div width to 100, padding 10, so that the element will occupy 120 pixels (10 * 100 + 2).
  • border-box - padding and border included in the width or height of the element in a set width: 100px-Sizing and Box:
    border-Box div element, his total width is 100px, regardless of its padding and borders have How many.

All elements are set to border-box, you can more easily change the size of the element, without fear of padding values ​​or a border element will be deformed or stretched wrap display.

5. The picture as a background

When the page is added to the picture, the picture is responsive particular need, it is best to introduce the use of background image attribute instead <img> tag.

It looks to use the picture is more complicated, but in fact it will make the picture style settings easier. With the background-size, background-position, and other attributes, maintain or change the image size and aspect ratio of the original will be more convenient.

For example
HTML

<section>
    <p>Img element</p>
    <img src="https://tutorialzine.com/media/2016/08/bicycle.jpg" alt="bicycle">
</section>

<section>
    <p>Div with background image</p>
    <div></div>
</section>复制代码

CSS

img {
    width: 300px;
    height: 200px;
}

div {
    width: 300px;
    height: 200px;
    background: url('https://tutorialzine.com/media/2016/08/bicycle.jpg');
    background-position: center center;
    background-size: cover;
}

section{
    float: left;
    margin: 15px;
}复制代码

One drawback background picture is the introduction of a Web page accessibility will be slightly affected, because screen readers and search engines can not properly get to the image. This problem can be solved by CSS object-fit properties, so far in addition to IE browser other browsers can use object-fit.

6. Better table borders

The HTML table is always difficult to read. They are difficult to make responsive, and very difficult to change the style in general. For example, if you want to add a simple table and cell borders, the most likely outcome is:

As you can see, there are many repeat border, it looks very pretty. Here's a quick way to remove all the double border: border-collapse: collapse, just after setting this property, the border of the table looks pleasing to the eye:

7. More friendly comments

Perhaps CSS is not a programming language, but the code still needs to be documented. Comments can add some simple code classification to distinguish themselves and their colleagues to facilitate post maintenance.

For large or important components of zoning you can use the following annotation style:

/*---------------
    #Header
---------------*/
header { }

header nav { }

/*---------------
    #Slideshow
---------------*/
.slideshow { }复制代码

For details and less important style single-line mode can use the comment:

/*   Footer Buttons   */
.footer button { }

.footer button:hover { }复制代码

Also, remember, CSS // no comment, only / ** / comment:

/*  正确  */
p {
    padding: 15px;
    /*border: 1px solid #222;*/
}

/*  错误  */
p {
    padding: 15px;
    // border: 1px solid #222;  
}复制代码

8. dash named

When the class ID or multiple words, use a hyphen (-), CSS is not case sensitive, can not be used camel named. Also, CSS are not recommended naming underscore the connection.

/*  正确     */
.footer-column-left { }

/*  错误  */
.footerColumnLeft { }

.footer_column_left { }复制代码

When it comes to naming, you can also consider BEM, which follows a set of principles that provide component-based development approach and increase consistency.

9. Do not repeat settings

Most CSS property values ​​are elements from the DOM tree of an upward inheritance, and therefore was only named as cascading style sheets. With font attributes, for example - it is always inherited from the parent, you do not have every element on the page are set individually.

Just set the font style to be added to the <html> or <body> element, and then have them automatically inherit down.

html {
    font: normal 16px/1.4 sans-serif;
}复制代码

Then we can change all of a unified text style on the page. Of course, CSS are not all properties are inheritable, for we still need to set these properties individually on each element.

10. Use the transform property to create animations

The best use transform () function to create displacement or size of animated elements, try not to directly change the width of elements, height and left / top / bottom / right property values.

The following example, we add the element to .ball a moving animation from left to right. Recommended transform: translateX () function instead of the left attribute.

.ball {
    left: 50px;
    transition: 0.4s ease-out;
}

/* 不建议 */
.ball.slide-out {
    left: 500px;
}

/* 建议 */
.ball.slide-out {
    transform: translateX(450px);
}复制代码

and transform all of its functions (translate, rotate, scale, etc.) almost no browser compatibility issues, free to use.

11. Do not DIY, multi-use code library

CSS community is very large, there are always new code base appears. They have a variety of uses, from tiny fragments to construct whole frame in response to the application of the formula. Most of them open source.

The next time you face a CSS problem, before you try devoting efforts to resolve it, check to see if a solution has been available on Github or Codepen.

Hold selector 12. The low weight

css selectors are not all equal. When the original learning CSS, I always think selector overwrites everything above it. However, it is not the case, as in the following example we explained:

HTML

<a href='#' id='blue-btn' class="active">按钮</a>复制代码

CSS

a{
    color: #fff;
    padding: 15px;
}
a#blue-btn {
    background-color: blue;
}
a.active {
    background-color: red;
}复制代码

We want to set the style .active class will take effect the button turns red. But it does not work because there is a top button ID selector, it also provided background-color, ID selector has a higher weight, the blue color of the button. Selector small right major specifications are as follows:

ID (#id) > Class (.class) > Type (例如 header)复制代码

Weight also superimposed, then a # button.active important than the right to a # button high. Start out with high weight selectors will lead you continue to use heavy weights higher selector at the back of maintenance, chose to use! Important, which is very recommended, it will be followed by specific reasons mentioned.

13. Do not use the! Important

Really, do not use! Important. Now it seems you can quickly solve the problem, but eventually could lead to a major rewrite. Instead, we should take the time to find the cause of CSS selectors do not work and change it.

The only! Important place that can be used when you want to override inline styles in HTML, but the inline style is also a bad habit, you should try to avoid.

14. The use of text-transform converted to uppercase letters

This section applies to the English environment is not suitable for Chinese

In HTML, you can write a word all capital letters to emphasize the meaning of the expression. such as:

<h3>Employees MUST wear a helmet!</h3>复制代码

If you need a piece of text is completely converted to uppercase, we can correctly write in HTML, and then converted by CSS. This will maintain the consistency of the context of the content.

<div class="movie-poster">Star Wars: The Force Awakens</div>复制代码
.movie-poster {
    text-transform: uppercase;
}复制代码

15.Em, Rem 与 px

Which unit set up with the size of the text elements should be used, em, rem, or px? There has always been a lot of controversy. The fact is, these three options are feasible, has its pros and cons.

At what point what kind of units used in the project is not a conclusion, the developers of different habits, different requirements of the project, may be used by different units. However, although there is no fixed rule, but each unit there are a few places to note is:

  • em - Set elements 1em, its size and font-size-related properties of the parent element. This unit is used to query media, especially for the development of responsive, but due to the em unit in each stage relative to the parent element is calculated, so to obtain a sub-element value of px corresponding em units, sometimes it is very troublesome.
  • rem - with respect to the size of the font-size <html> element calculation, rem changed such that all titles and uniform size of paragraph text on a page becomes very easy.
  • px - pixel unit is the most accurate, but not for adaptive design. px being reliable, and easy to understand, we can fine size and moving the control element to 1px.

Most importantly, do not be afraid to try, try all methods to see what works best for. Sometimes, em and rem can save a lot of work, especially when building responsive page.

16. For large projects using a pre-processor

You must have heard them - Sass, Less, PostCSS, Stylus. CSS preprocessor is the future. They provide services such as variables, functions CSS, selectors nesting and many other cool features that make CSS code easier to manage, especially in large projects.

As a simple example, the following code is a fragment of a SASS, which uses some CSS to variables and functions:

$accent-color: #2196F3;
a {
    padding: 10px 15px;
    background-color: $accent-color;
}
a:hover {
    background-color: darken($accent-color,10%);
}复制代码

The only downside of the preprocessor is any course they need to be compiled into a normal CSS. The launch of the CSS custom property is pretreated in the true sense.

17. Use AutoPrefixer achieve better compatibility

CSS browser prefixes is one of the most annoying things that need to prefix each attribute is inconsistent, in the end you never know which one needs, if you really take it one by one manually added to the style sheet, it is undoubtedly a silly nightmare.

Fortunately, there are tools to automatically provide added functionality to the browser prefixes we can even decide which browsers need to support:

18. CSS file compression

In order to improve the site and page loading speed and load applications, you should use the resource after compression. Compressed version of the file will remove all gaps and duplication, thereby reducing the volume of the total file. Of course, this process also makes a style sheet completely unreadable, so use .min version in a production environment, as well as developing retain conventional version.

There are many different ways to compress CSS code:

Depending on your workflow, you can use any of these ways.

19.Caniuse

For the CSS properties of the Web browser inconsistencies still exist in many places compatibility. Use caniuse to check whether you are using the attribute has been widely supported? You need to prefix? Or whether there is a place to note in the browser? With caniuse you will be more handy when writing CSS.

20. Verify

Verify CSS may not validate HTML or JavaScript code that important, but by running tool at your code still very useful. It will tell whether you made any errors, warnings, incorrect usage, and provide tips to improve your code for you.

Like compression and Autoprefixer as there are free tools you can use:




Reproduced in: https: //juejin.im/post/5d0b228bf265da1b6a349a46

Guess you like

Origin blog.csdn.net/weixin_34004576/article/details/93182123