A detailed description of CSS code refactoring

Source: Internet
Author: User
This article mainly introduces the CSS code refactoring, small series feel very good, and now share to everyone, but also for everyone to do a reference. Follow the small series together to see it, hope to help everyone.

1. Refactoring and architecture

Refactoring refers to rewriting the code without changing the behavior of the code, making it more concise and easy to reuse.

A schema is a combination of various parts of a software project.

Excellent architecture:

    1. Predictable: You can make accurate assumptions about how the software works and how it is structured

    2. Reusable: Use the same code in multiple places without rewriting

    3. Expandable: Easy to add new content

    4. Maintainable: Modify a code without altering other code at scale

2. Precedence of CSS Selectors

Use (A, B, C, D) to indicate that the priority is a>>b>>c>>d, where:

    1. There are inline style properties when a=1, otherwise a=0

    2. B is the number of ID selectors

    3. C is the number of class selectors, property selectors, pseudo-classes

    4. D is the type selector, the number of pseudo-elements

(PS: The difference between pseudo-class and pseudo-elements)

!important has the highest priority and can override inline styles. cannot be added to inline style properties.

3. How to write high-quality CSS

Using annotations

Note the contents of the record include:

    1. File contents

    2. Dependency, usage of selectors

    3. Reasons for using a specific claim (hack, etc.)

    4. Obsolete styles that should not continue to be used

/** Navigation link Style * * @see templates/nav.html*/.nav-link {  ...}. Nav-link:hover {  border-bottom:4px solid #333;  /* Prevent adding a 4px lower border causing the element to move */  padding-bottom:0;} /* @deprecated */.nav-link {  ...}

Keep the selector simple

/* Not recommended */p > NAV > Ul > li > A {}/* not recommended */a.nav-link {}/* recommended */.nav-link {}

However, not all scenarios should follow this recommendation, as follows to add style to the text and border of the input box.

. Error {  color: #f00;} Input.error {  border-color: #f00;}

Separating CSS and JavaScript

The class and ID used in JavaScript to select elements should no longer be used to add styles to elements. When you modify an element style with JavaScript, you should do so by adding and removing classes.

It is recommended that you add js-to the JavaScript-only class and ID, or that the ID is used only for JavaScript selection elements, and that the class is used for styles.

ID and class name make sense

Create a better box

The dimensions of the box are calculated using Content-box and Border-box, and it is recommended to stick to a method in a project, such as:

*,*::after,*::before {}

(PS::: After notation is introduced in CSS3: The notation is used to distinguish between pseudo-classes and pseudo-elements.) Browsers that support CSS3 also support the notation introduced in CSS2: After, IE8 only: After)

Categorize styles

Defining styles by Purpose helps create better architectures, because organizing styles into different categories makes the code more predictable and easier to reuse.

Common styles

Because the default styles for different browsers vary slightly, a common style is required to set the default value style for the properties of various elements, making them available in different browsers

Consistent performance.

It is recommended that Nicolas Gallagher and Jonathan Neal develop NORMALIZE.CSS, which can be properly pruned according to their own projects.

Base style

Use a type selector and a binding character (for example, UL UL for UL below) or pseudo-class to add a more granular style to HTML elements. For example: Color, font-family, Font-size, letter-spacing, line-height, margin, padding and so on.

HTML elements can be divided into: block elements, title and text elements, anchor elements, text semantic elements, lists, tables, forms, and so on, different elements in the basic style of the settings slightly different, can refer to the element base style sheet.

Component styles

Components are important for reusability, such as: Buttons, drop-down menus, modal boxes, tabs, and so on.

    1. Defines the behavior that needs to be implemented, that is, the effect that the component achieves, and the organization HTML structure

    2. Add styles to elements in components to ensure reusability

    3. Override the style of the element container as needed. such as a confirmation button, a warning button, a success button, and so on, define the component's container element with different class names

    4. Dimensions are set in the parent element of the component

Feature Styles

It is reasonable to use!important to define class properties, which are used when JavaScript is manipulating styles. such as adding the following class to implement element hiding:

. hidden {  display:none!important;}

Browser-specific styles

Although browser behavior tends to be unified in the future, some old browsers still have quirks at the moment. We have to use some hack styles to solve these quirks, and we recommend that you put these styles in a single style sheet and add references with conditional comments.

<!--[if IE 8]>  <link rel= "stylesheet" href= "Ie8.css"/><![ Endif]-->

Maintain code

Code specification

The code specification is a good code writing method that is documented to form a guide to encourage all members of the team to write code in the same way. Specifications should be reviewed and updated regularly. CSS code specifications typically specify convenient specifications for annotations, formatting, naming, selector usage, and so on.

Pattern Library

A pattern library is a set of user interface patterns used by a site to bring together all components. The advantage is that members of participating projects can understand the various modules of the site, familiarize themselves with the principles behind them, and help ensure the consistency of the user interface.

Recommend several excellent pattern libraries:

    1. Mailchimp ' s Pattern Library

    2. [Carbon Design System] (http://carbondesignsystem.com/style/color/swatches)

    3. Code for America

Organization and refactoring Strategies for code

Organize your CSS from the least accurate to the most precise style

Before we sorted the styles, we now organize the CSS code in the order in which they are produced:

    1. General style: Set a benchmark to eliminate inconsistencies between different browsers

    2. Base style: Provides basic styling for all elements of a site, such as color, spacing, line height, font, and so on, with no need to rewrite

    3. Component and Container styles: Based on the underlying style of the above step, define the style with a class

    4. Structured styles: This style is commonly used to create layouts, define dimensions, etc.

    5. Feature style: The most precise style, style implemented for a single purpose, such as a warning box style

    6. Browser-specific styles

PS: Media queries are close to the relevant declaration block, which can provide more background information about how the style works.

Review CSS before refactoring

The following review is very helpful for refactoring:

    1. List of properties used

    2. Number of colors

    3. Highest and lowest selector priority used

    4. Selector length

CSS Dig is a plugin for Google Chrome that can help you get the information above.

Refactoring policy

Multiple small-scale refactoring is recommended to avoid introducing errors in large-scale refactoring.

(1) Remove the Zombie code:

There are no declaration blocks used, duplicate declaration blocks, and declaration statements.

(2) Separating CSS and JavaScript

(3) separating the base style

If a type selector has been used more than once, create a new rule set, find the most commonly used attribute, and add it to the new rule set. Remove duplicate properties from other rule sets because they can inherit the new defined base style.

/* Refactor before */body > P > H1 {  color: #000;  font-size:32px;  margin-bottom:12px;}. section-condensed H1 {  color: #000;  font-size:16px;}. Order-form H1 {  color: #333;  Text-decoration:underline;} /* After refactoring */h1 {  color: #000;  Font-family:helvetica, San-serif;  font-size:32px;  line-height:1.2;} Body > P > H1 {  margin-bottom:12px;}. section-condensed H1 {  font-size:16px;}. Order-form H1 {  color: #333;  Text-decoration:underline;}

(4) Remove the redundant ID

/* Not recommended */#main-header Ul#main-menu {}/* recommended */#main-menu {}

(5) Define reusable components, remove duplicate CSS

(6) Delete inline CSS

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.