20 Suggestions for writing modern CSS code

Source: Internet
Author: User
Tags postcss

CSS Cascading Style Sheets

CSS (cascading style sheets) is the cascading style sheet. It is a computer language used to represent file styles such as HTML (an application of the standard Universal Markup Language) or XML (a subset of the standard Universal Markup Language).


Understand what margin Collapse

Unlike many other properties, the margin in the vertical direction of the box model collapses when it encounters, meaning that when the bottom margin of an element is adjacent to the top margin of another element, only the larger values in the two are preserved, as can be learned from this simple example:

. square {    width:80px;    height:80px;}. Red {    background-color: #F44336;    margin-bottom:40px;}. Blue {    background-color: #2196F3;    margin-top:30px;}

In the example above, we find that the margins of the red and blue squares are not added to the 70px, but only the lower margin of the red is preserved. We can use some methods to avoid this behavior, but it is much more harmonious to use the Margin-bottom property as much as possible.

Using Flexbox for layout

In traditional layouts we are accustomed to using floats or inline-blocks, but they are more suitable for formatting documents than for the entire site. Flexbox, however, is a specialized tool for layout. The Flexbox model allows developers to use a number of convenient and extensible properties for layout, estimating that you will be reluctant to use it once:

. container {    Display:flex;    /* Don ' t forget to add prefixes for Safari */display:-webkit-flex;}

We have provided a lot of introductions and tips on Tutorialzine on Flexbox, such as 5 Flexbox techniques you need to Know about.

Using the CSS Reset

Although over the years, with the rapid development of the browser and the unification of the specification, the browser feature fragmentation of the situation has improved, but there are still a lot of different browser behavior differences. The best way to solve this problem is to use one of the CSS reset to set a uniform style for all the elements, so that you can start working on a relatively uniform and clean style sheet. The current popular reset library has normalize.css, Minireset, and ress, all of which can fix the differences between many known browsers. And if you're not going to use an external library, the following basic rules are recommended:

* {    margin:0;    padding:0;    Box-sizing:border-box;}

The above rules don't seem to work, but it would be a hassle if different browsers set the default value for you for different margins/padding by default.

Everything should be Border-box

Although many beginners do not understand the box-sizing attribute, it is really quite important. The best way to understand it is to take a look at two of its values:

The default value is Content-box, that is, when we set the Heght/width property of an element, it only works on its content size. And all the padding and edges are accumulated on top of it, for example, a <div> tag is set to a width of 100 and the padding is 10, then the final element will occupy 120 (100 + 2*10) pixels.

Border-box: The inner margin and edge are included in the width/height, for example, set the width:100px <div> regardless of the internal margin or the length of the edge is set to how much, the size of its occupy is 100px.

Setting the element to Border-box will make it easier for you to style the layout so that you can set the height limit on the parent element without worrying about the child element's padding or edges breaking the limit.

Using images as a background map

If you need to present a picture in a responsive environment, a simple trick is to use the image as a background image of <div> instead of using the IMG tag directly. In this way, with the two properties of Background-size and background-position, it is convenient to scale proportionally:

img {    width:300px;    height:200px;} div {    width:300px;    height:200px;    Background:url (' http://cdn.tutorialzine.com/wp-content/uploads/2016/08/bicycle.jpg ');    Background-position:center Center;    Background-size:cover;} section{    Float:left;    margin:15px;}

But this way is also flawed, such as you can not set the image of lazy loading, the picture can not be crawled by the search engine or other similar tools, there is a good property called Object-fit can solve the problem, but this property is not very well-supported browser support.

Better Table Borders

Using tables for layout in HTML has always been a headache, and they are simple to use, but they are not responsive and do not make it easy to set up global styling. For example, if you want to add a style to the side of the table and the side of the cell, you might get the following result:

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 repetitive edges that can lead to visually uncoordinated situations, so we can do this by setting up Border-collapse:collapse:

Annotation format optimization

CSS is not a programming language, but it still needs to add comments to ensure the readability of the overall code, as long as you add a few simple comments can not only make it easier for you to organize the entire style sheet is also able to let your colleagues or future self-understanding better. For comments on the entire block in CSS or for annotations in Media-query, the recommendation is to use the following form:

/*---------------    #Header---------------*/header {}header nav {}/*---------------    # Slideshow---------------*/.slideshow {}

The details of the design or some of the unimportant components can be used as a single comment:

/*   Footer Buttons   */.footer button {}.footer Button:hover {}

Also, do not forget that there is no//such comment in the CSS:

/* Do  */p {    padding:15px    ; /*border:1px solid #222; */}/*  Don ' t  */p {    padding:15px;    border:1px solid #222;  }

Using Kebab-case to name variables

The name of the style class or ID name needs to be added between multiple words-the symbol, the CSS itself is case insensitive so you can not use CamelCase, on the other hand, long ago also does not support the underscore, so now the default naming method is to use-:

/* Do     */.footer-column-left {}/*  Don ' t  */.footercolumnleft {}.footer_column_left {}

When it comes to specific variable naming specifications, the recommendation is to use the BEM specification, which guarantees the naming consistency based on the component style as long as it follows some simple principles. You can also refer to CSS tricks for more detailed descriptions.

Avoid duplicate code

The CSS properties of most elements are inherited from the root of the DOM, which is also the origin of their name as cascading style sheets. We take the Font property as an example, which is often inherited from the parent property, so we don't need to set this property separately for the element. We just need to add the attribute to the HTML or body and then pass the hierarchy down:

HTML {    font:normal 16px/1.4 Sans-serif;}

Add CSS animations using transform

It is not recommended to change the width and height properties of an element directly or left/top/bottom/right these properties to animate, but rather to use the transform () property to provide smoother transformations and to make the code more readable:

. ball {    left:50px;    Transition:0.4s Ease-out;} /* Not cool*/.ball.slide-out {    left:500px;} /* Cool*/.ball.slide-out {    Transform:translatex (450px);}

Transform's several properties translate, rotate, scale have better browser compatibility can be used with ease.

Don't reinvent the wheel.

Now the CSS community is very large, and there is always a new variety of libraries open source. These libraries can help us solve the entire framework for building complete, responsive applications from small pieces of code. So the next time you come across a CSS problem, try to search for a workable solution on GitHub or Codepen before you're ready to roll up your sleeves.

Use low-priority selectors whenever possible

Not all CSS selectors have the same priority, and many beginners are considering the new features to replicate all the inheritance features when using CSS selectors, but this is troublesome when an element is in many states, such as the following example:

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

We would have liked to add the. Active class to the button and then make it appear red, but in the example above it is obviously not useful because the button has already set the background color with the ID selector, which is known as the higher Selector specificity. In general, the priority order of selectors is: ID (#id) > class (. Class) > Type (header)

Avoid using!important

Seriously, be sure to avoid using!important, which may lead you to an endless property rewrite in future development, and you should choose a more appropriate CSS selector. The only scenario where you can use the!important property is when you want to replicate certain inline styles, but the inline style itself is something to avoid.

Use the Text-transform property to set text capitalization

<div class= "Movie-poster" >star wars:the force awakens</div>.movie-poster {    Text-transform:uppercase ;}

Em, Rem, and Pixel

There has been a lot of discussion about how people should use Em,rem, as well as px as an element size and text size, and I think that these three size units have their applicability and not applicable places. Different development and projects have their own specific settings, so there is no general rule to decide which unit to use, here are a few considerations that I summarize:

em– its basic unit is the Font-size value of the current element, often applicable to media-queries, EM is particularly suitable for responsive development.

rem– is a unit that is relative to the HTML attribute, which guarantees a true response dimension to the text paragraph.

Px–pixels does not have any dynamic extensibility, they are often used to describe absolute units, and can maintain a certain consistency between the setting value and the final display effect.

Using a preprocessor in a large project

Presumably you've heard of Sass, less, postcss, stylus these preprocessor with the corresponding syntax. Preprocessors can allow us to apply future CSS features to current code development, such as variable support, functions, nested selectors, and many other features, here we take sass as an example:

$accent-color: #2196F3; a {    padding:10px 15px;    Background-color: $accent-color;} a:hover {    Background-color:darken ($accent-color,10%);}

Using autoprefixers to improve browser compatibility

The use of specific browser prefixes is one of the common tasks in CSS development, and different browsers and different attributes are not the same for prefixes, which makes it impossible to remember all the prefix rules during the encoding process. And in writing style code also need to add a specific browser prefix support is also a nuisance, fortunately there are many tools to assist us in this development:

Online Tools:autoprefixer

Text editor plugins:sublime text, Atom

Libraries:autoprefixer (POSTCSS)

Using minified code in a production environment

In order to increase the loading speed of the page, we should use the compressed resource code by default in the production environment. During compression, all whitespace and repetition are eliminated to reduce the size of the entire file. Of course, after compressing the code is not readable, so in the development phase we should still use the normal version. There are a number of existing tools for CSS compression:

Online tools–css Minifier (API included), CSS Compressor

Text editor plugins:sublime text, Atom

Libraries:minfiy (PHP), Csso and Cssnano (Postcss, Grunt, Gulp)

Choose which tool must be dependent on your own workflow ~

See more Caniuse

Different browsers vary greatly in compatibility, so if we can target the browsers we need to adapt, we can query the browser version of a particular feature on caniuse, whether we need to add a specific prefix or whether there are bugs on a platform, and so on. However, the use of caniuse is certainly not enough, we also need to use some additional services to detect.

Validate: Checksum

The checksum for CSS may not be as important as HTML validation or JavaScript validation, but it would make sense to check your CSS code with the Lint tool before the official release. It will tell you about potential errors in your code, suggest some code that does not conform to best practices, and give you some suggestions for improving the performance of your code. Like Minifers and Autoprefixers, there are also a number of tools available:

Online tools:w3 Validator, CSS Lint

Text editor plugins:sublime text, Atom

Libraries:lint (node. js, Postcss), Css-validator (node. js)


The above is the 20 write the modern CSS code recommendations of content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • Related Article

    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.