20 suggestions for writing modern CSS code and writing modern css code

Source: Internet
Author: User

20 suggestions for writing modern CSS code and writing modern css code

Understand what Margin Collapse is

 

Unlike many other attributes, Margin in the vertical direction of the box model will collapse when it encounters, that is, when the bottom Margin of an element is adjacent to the top Margin of another element, only the larger values of the two are retained. You can learn from the following simple example:

 

. Square {

Width: 80px;

Height: 80px;

}

. Red {

Background-color: # F44336;

Margin-bottom: 40px;

}

. Blue {

Background-color: #2196F3;

Margin-top: 30px;

}

In the above example, we will find that the margin of the red and blue squares is not added to get 70px, but only the bottom margin of the red is retained. We can use some methods to avoid such behavior. However, we recommend that you use the margin-bottom attribute as much as possible.

Layout with Flexbox

 

In the traditional layout, Floats or inline-blocks are used, but they are more suitable for formatting documents than the entire website. Flexbox is a dedicated tool for layout. The Flexbox model allows developers to use a lot of convenient and scalable attributes for layout. It is estimated that once you use it, you will be reluctant:

 

. Container {

Display: flex;

/* Don't forget to add prefixes for Safari */display:-webkit-flex;

}

Use CSS Reset

Although browser feature fragmentation has improved over the years with the rapid development of browsers and standardized unification, there are still many behavior differences between different browsers. The best way to solve this problem is to use a CSS Reset to set a uniform style for all elements, so that you can start working on a relatively unified and clean style sheet. Currently, the popular Reset libraries include normalize.css, minireset, and ress, which can correct the differences between many known browsers. If you do not want to use an external database, we recommend that you use the following basic rules:

 

*{

Margin: 0;

Padding: 0;

Box-sizing: border-box;

}

The above rules seem useless, but it will be quite troublesome if different browsers set different default values for the outer and inner margins by default.

Everything should be Border-box

Although many beginners do not understand the box-sizing attribute, it is indeed very important. The best way to understand it is to look at its two values:

 

The default value is content-box, that is, when we set the heght/width attribute of an element, it only applies to its content size. All the margins and edges are accumulated on them. For example, if a <div> label is set to 100 in width and 10 in width, the final element occupies 120 (100 + 2*10) pixels.

 

Border-box: the padding and edge are included in width/height. For example, if width: 100px is set

<Div>

Regardless of the padding or edge length, the occupied size is 100px.

 

Setting the element to border-box will facilitate style layout, in this way, you can set a high-Width limit on the parent element without worrying that the padding or edge of the child element breaks this limit.

 

Use Images as a background image

 

To display an image in a responsive environment, you can use the image as the background image of a <div> instead of using the img label directly. In this way, combined with the background-size and background-position attributes, You can conveniently scale proportionally:

 

Img {

Width: 300px;

Height: 200px;

}

Div {

Width: 300px;

Height: 200px;

Background: url ('HTTP: // cdn.tutorialine.com/wp-content/uploads/2016/08/bicycle.jpg ');

Background-position: center

Background-size: cover;

}

Section {

Float: left;

Margin: 15px;

}

However, this method is also flawed. For example, you cannot set the image to be loaded lazily, the image cannot be captured by search engines, or other similar tools, there is a good attribute called object-fit to solve this problem, but the browser support for this attribute is not very complete at present. (Web Front-end learning and communication group: 328058344 chat prohibited, not welcome !)

Better Table Borders

It has always been a headache to use Tables for layout in HTML. They are easy to use, but they cannot perform responsive operations and are not convenient to set global styles. For example, if you want to add a style for the edge of the Table and the edge of the cell, the possible result is as follows:

Table {width: 600px; border: 1px solid #505050; margin-bottom: 15px; color: #505050 ;}td {border: 1px solid #505050; padding: 10px ;}

 

 

 

The problem here is that there are a lot of duplicate edges that may cause visual inconsistencies. Then we can set border-collapse: collapse

For processing:

 

Comment format Optimization

 

Although CSS is not a programming language, it still needs to add comments to ensure the readability of the entire code, simply adding some simple annotations not only makes it easy for you to better organize the whole style sheet, but also allows your colleagues or yourself to better understand it in the future. We recommend that you use the following format for the whole block comment in CSS or the comment in Media-Query:

 

/*---------------

# Header

---------------

*/Header {} header nav {}/*---------------

# Slideshow

---------------

*/. Slideshow {}

The design details or unimportant components can be annotated in the following single line:

 

/* Footer Buttons */

. Footer button {}

. Footer button: hover {}

At the same time, do not forget that CSS does not contain //

In this way:

 

/* Do */p {

Padding: 15px;/* border: 1px solid #222 ;*/

}

/* Don't */p {

Padding: 15px; // border: 1pixel solid #222;

}

Use Kebab-case to name variables

For style class names or ID names, you must add a-symbol between multiple words. CSS itself is case insensitive, so you cannot use camelCase. On the other hand, underlines are not supported long ago, so the default naming method is to use -:

 

/* Do */

. Footer-column-left {}

/* Don't */

. FooterColumnLeft {}

. Footer_column_left {}

When it comes to specific variable naming conventions, we recommend that you use the BEM specification. You only need to follow some simple principles to ensure component-style naming consistency. You can also refer to CSS Tricks for more details.

 

Avoid repeated code

 

The CSS attributes of most elements are inherited from the root of the DOM, which is also the origin of the Cascading Style Sheet. Taking the font attribute as an example, this attribute is often inherited from the parent attribute, so we do not need to set this attribute for the element separately. We only need to add this attribute to html or body and pass it through the hierarchy:

 

Html {

Font: normal 16px/1.4 sans-serif;

}

Add CSS Animations using transform

 

It is not recommended to directly change the width and height attributes of the element or left/top/bottom/right

These attributes are used to achieve the animation effect. Instead, the transform () attribute should be used first to provide a smoother transformation effect and make the code more readable:

 

Left: 50px;

Transition: 0.4 s timeout-out;

}/* Not Cool */. ball. slide-out {

Left: 500px;

}/* Cool */. ball. slide-out {

Transform: translateX (pixel px );

}

Transform attributes: translate, rotate, and scale

Both have good browser compatibility and can be safely used.

 

Do not duplicate wheels

 

Currently, the CSS community is very large and there are constantly new open-source libraries. These libraries help us solve the problem from small code snippets to the full framework for building a complete responsive application. So if you encounter any more CSS problems next time, you can try to search for feasible solutions on GitHUB or CodePen before you plan to pick up your sleeves.

 

Use a selector with a lower priority as much as possible

 

Not all CSS selectors have the same priority. Many beginners use CSS selectors to reproduce all inheritance features with new features, however, this is troublesome when an element is in multi-state, for example, the following example:

 

A {

Color: # fff;

Padding: 15px;

}

A # blue-btn {

Background-color: blue;

}

A. active {

Background-color: red;

}

We wanted. the active class is added to the button and displayed in red. However, in the preceding example, the background color has been set by the ID selector, that is, the so-called Higher Selector Specificity. Generally, the priority of the selector is: ID (# id)> Class (. class)> Type (header)

 

Avoid using! Important

 

Seriously, do not use it! Important, which may lead to endless attribute rewriting in future development. You should select a more appropriate CSS selector. The only one can be used! The important attribute scenario is when you want to repeat some intra-row styles, but intra-row styles also need to be avoided.

 

Set text uppercase using the text-transform attribute

 

<Div class = "movie-poster"> Star Wars: The Force Awakens </div>.

Movie-poster {

Text-transform: uppercase;

}

Em, Rem, and Pixel

 

There have been a lot of discussions about how people should use em, rem, and px as element sizes and text sizes, and I think, the three dimension units have their applicability and inapplicability. Different Development and projects have specific settings, so there is no general rule to decide which unit to use. Here are my summary:

 

Em-the basic unit is the font-size of the current element.

Value, which is often used in media-queries, and em is especially suitable for responsive development.

 

Rem-relative to html

Attribute unit to ensure the true responsive size of text paragraphs.

 

Px-Pixels does not have any dynamic scalability. They are often used to describe absolute units and can be consistent between the set value and the final display effect.

 

Use a pre-processor in a large project

 

It is estimated that you have heard of Sass, Less, PostCSS, and Stylus preprocessors and their corresponding syntaxes. Preprocessors allows us to apply future CSS features in current code development, such as variable support, functions, nested selectors, and many other features. Here we take Sass as an example:

 

$ Accent-color: #2196F3; {

Padding: 10px 15px;

Background-color: $ accent-color;

}

A: hover {

Background-color: darken ($ accent-color, 10% );

}

Use Autoprefixers to improve browser compatibility

Using a specific browser prefix is one of the common tasks in CSS development. Different browsers and attributes have different prefix requirements, this makes it impossible for us to remember the prefix rules in the encoding process. In addition, adding a specific browser prefix to the style code is also troublesome. Fortunately, there are many tools that can help us with this development:

 

Online tools: Autoprefixer

 

Text editor plugins: Sublime Text, Atom

 

Libraries: Autoprefixer (PostCSS)

 

Use Minified code in a production environment

 

To speed up page loading, we should use compressed resource code by default in the production environment. During the compression process, all the gaps and duplicates will be removed to reduce the size of the entire file. Of course, the compressed code is unreadable, so we should use a normal version in the development stage. There are many existing tools for CSS compression:

 

Online tools-CSS Minifier (API encoded DED), CSS Compressor

 

Text editor plugins: Sublime Text, Atom

 

Libraries: Minfiy (PHP), CSSO and CSSNano (PostCSS, Grunt, Gulp)

 

Which tool to choose depends on your own workflow ~

For more information, see Caniuse.

Different browsers vary greatly in compatibility. Therefore, if we can query the browser version adaptation of a feature on caniuse, whether to add a specific prefix or whether a Bug exists on a platform. However, simply using caniuse is definitely not enough. We also need to use some additional services for detection.

 

Validate: Verification

 

CSS verification may not be as important as HTML verification or JavaScript verification, but it makes sense to use the Lint tool to verify a wave of your CSS code before the official release. It will tell you potential errors in the code, prompt you some code that does not conform to the best practices, and give you some suggestions to improve the Code performance. Like Minifers and Autoprefixers, there are also many available tools:

 

Online tools: W3 Validator, CSS Lint

 

Text editor plugins: Sublime Text, Atom

 

Libraries: stylelint (Node. js, PostCSS), css-validator (Node. js)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.