20 CSS code usage precautions in front-end combat project

Source: Internet
Author: User
Tags css validator
This time to bring you the front-end combat project in 20 CSS code use precautions, the following is the actual case, together to see.





01. Use Margin properties with caution



Unlike other properties, the margin in the vertical direction will collapse when it encounters. This means that if the bottom margin of an element encounters the top margin of another element, the larger of the two will be left. The following is a simple example.




<p class="square red"></p>

   <p class="square blue"></p>

   .square {

       width: 80px;

       height: 80px;

   }

   .red {

       background-color: #F44336;

       margin-bottom: 40px;

   }

   .blue {

       background-color: #2196F3;

       margin-top: 30px;

   }


In fact, the above two elements in the vertical direction of the distance is not 70px, but 40px, the blue square margin is not counted. There are many ways to eliminate this default behavior, but the best way is to use only the margin attribute in one direction, such as Margin-bottom.



02. Using the Box model layout



The box model naturally has its reasons for existence. float and Inline-block can of course work, but they are the underlying tools for styling documents, not the entire site. In a sense, Flexbox is designed to make it easier and more accurate to create the layout we want.



The Flexbox model provides a range of properties that give developers greater flexibility, and once you're familiar with them, it's easy to create any responsive layout. Browser support for Flexbox is also close to perfect, so there is no reason to stop you from using Flexbox.



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


03. Perform CSS Reset



Although the situation has improved over the years, there are still many differences in the default behavior of browsers. The best way to solve this problem is to use a CSS reset file to reset the default style for all elements. This allows you to work in a pure style environment and produce the same results in all browsers.



There are a lot of libraries doing this work very well, such as Normalize.css, Minireset, and ress, correcting inconsistencies between browsers. If you don't want to use the library, you can also make a simple CSS reset yourself, like this.



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


This may seem harsh, but eliminating the default margin and padding will make it easier for us to place our elements without worrying about the extra space it takes. Box-sizing:border-box is a very useful attribute, and we will describe this property below.



04. Use Border-box for all elements



Many beginners do not know the box-sizing attribute, but it is really important. The best way to learn about it is to look at its two optional values.



Content-box (default)-When we set the width and height of the element, but that's just the size of the content. All padding and border are not included in the content, that is, outside the content.



For example, if we have a p whose width is 100px and padding is 10px, then its actual width is 120px.



Border-box-padding and border are included in the width and height. If the width of a p is 100px and the Box-sizing:border-box is set, its width will always be 100px, no matter how many padding and border you add.



Setting Border-box for all the elements will help styling, and you won't have to do tedious math.



05. Image as background when you add pictures for your site, especially if you want to do responsive design, use a P tag and set the background attribute instead of the element.



It seems that the extra work doesn't make any difference, but in fact it's better for you to style your pictures, keep them in their original size or scale, depending on the background-size,background-size and some other properties.




<section>

       <p>Img element</p>

       <img src="" alt="bicycle">

   </section>

   <section>

       <p>p with background image</p>

       <p></p>

   </section>

   img {

       width: 300px;

       height: 200px;

   }

   p {

       width: 300px;

       height: 200px;

       background: url('');

       background-position: center center;

       background-size: cover;

   }

   section{

       float: left;

       margin: 15px;

   }


One drawback of this technique is that the accessibility of your pages can be slightly more striking, as your images will not be crawled correctly by screen readers and engines. This problem can be solved by object-fit, but it is not supported by all browsers.



06. Better Table Border



Table in HTML is of little meaning. They are very eccentric, difficult to design in response, and difficult to match the overall style. For example, if you want to add a border to a table and its elements, you might get the following result.






As you can see, it has a lot of duplicate borders and doesn't look very good, there is a very quick and easy way to remove the double-sided box, which is to add border-collapse:collapse to the table.






It looks a lot better then.



07, a better way to annotate



CSS may not be a programming language, but its code still needs to be recorded, so some simple comments will be helpful to your colleagues or future self!



For some of the larger modules in CSS, such as major modules or media queries, use stylized annotations and leave some blank lines behind.




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

    #Header

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

header { }

header nav { }

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

    #Slideshow

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

.slideshow { }


Some of the details in the design, or modules that are not particularly important, can be commented in a single line.



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


Also, it is important to note that there is no//comment in the CSS, so you need to use the/* */sign when you need to comment.




/*  Do  */

p {     

  padding: 15px;

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

}

/*  Don't  */

p {

    padding: 15px;

    // border: 1px solid #222;  

}


08. Named Connections



When class or ID more than one word, need to use-symbolic connection, CSS is not sensitive to case, so camel nomenclature is not a good choice. Long ago, underscores were not supported, so dashes became the default conventions.



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


09. Do not repeat settings



Many of the property values of CSS are inherited from the upper level of the DOM tree, and are therefore named Cascading style sheets. Let's take font for example-it almost always inherits from the parent node, and you don't need to set that property for each element in the page.



You just have to set the font style for


html {
        font: normal 16px/1.4 sans-serif;
    }


Of course, you can change this style according to your own needs in any child element. All I have to say is that you can use inheritance to get the properties and don't go to one by one to specify.



10. CSS Animations and Transformations



Do not animate elements by directly changing the width and height of the elements, or change the left/right/top/bottom. The best way to do this is to use the transform () property because it provides a smoother transition and makes your intentions easier to understand as you read the code.



Here's an example where we want to animate a ball and let it slide to the right. Do not change the left value, preferably using TranslateX ().




.ball {

       left: 50px;

       transition: 0.4s ease-out;

   }

   /* Not Cool*/

   .ball.slide-out {

       left: 500px;

   }

   /* Cool*/

   .ball.slide-out {

       transform: translateX(450px);

   }


Transform and all of its methods (translate, rotate, scale, etc.) have almost consistent browser compatibility and you are free to use them.



11, do not DIY, use the library



The CSS community is huge and new libraries are constantly appearing. Libraries are offered for a variety of purposes, from small fragments to perfect frameworks for building responsive programs, and most of them are open source.



So the next time you encounter a CSS problem, when you want to do it yourself, it's best to go to Github or Codepen to find out if there's a solution available.



12, keep the selector of the specificity of low



Not all CSS selectors are raw and equal, and when novice developers write CSS code, they usually expect the selectors they write to overwrite all previous existing styles. But things are not always the way we think, as in the following example:




a{

        color: #fff;

        padding: 15px;

    }

    a#blue-btn {

        background-color: blue;

    }

    a.active {

        background-color: red;

    }


We want to add the. Active class to Red for all buttons, but this is not working because the button has been set by an ID selector background-color, and the ID selector has a higher degree of specificity. The rules between them are like this:



ID (#id) > class (. Class) > Type (such as header).



The degree of specificity can be stacked, so the specificity of a#button.active is higher than A#button. Using a high-specificity selector will allow you to constantly use higher-level overrides for existing selectors, which will eventually result in!important effects.



13. Do not use!important



Very seriously tell you, do not use!important. A quick fix on the fly can lead to a lot of rewriting in the future. Instead, find out why your CSS selector isn't working, and try to fix it.



It is only acceptable to use!important in one scenario, that is, you want to overwrite the inline styles defined in the HTML. and writing inline styles is a very bad way, and it's recommended to stop using them.



14. Using Text-transform



In HTML, when you use uppercase letters it may be for some semantic purpose, say you want to emphasize the importance of a word.


<h3>Employees MUST wear a helmet!</h3>


If you set a set of text to uppercase for some purpose, you can write the text normally in HTML and then convert its case using CSS. They all look the same, but if it's not in context, your content will make more sense.


<p class="movie-poster">Star Wars: The Force Awakens</p>

    .movie-poster { text-transform: uppercase;}


The same applies to uppercase or lowercase strings - the text-transform attribute can handle them very well.

15, Em, Rem and Pixel

There is a lot of debate about whether em, rem or px should be used to size elements and text. The fact is that all three are feasible and have their own strengths and weaknesses.

All developers and projects are different, so there should be no strict rules explaining when to use which one. Here are some tips and good practices:

The size of em - 1 em is related to the font size of the immediate parent element. Often used for media queries, em is great for responsive design, but converting the em value of each element to px is very difficult to calculate because you might want to track elements step by step on the DOM tree.

Rem - Based on the font-size in the <html> element, rem makes it easy to scale the titles and paragraphs in the page. It's a great way to keep the default font-size in <html> and set rem for other elements.

Px - Pixel is the most accurate way to control, but it's not friendly in responsive design because it doesn't scale automatically as the screen size changes. They are reliable, easy to understand, and present a good visual connection between values and actual results.

The next thing I want to say is, don't be afraid to try. Go use them and find out which one is your favorite. Sometimes em and rem are easy, especially for responsive interfaces.

16. Use a preprocessor in a large project

You may have heard of them - Sass, Less, PostCSS, Stylus. The preprocessor is the next stage in the development of CSS. They provide features such as variables, CSS functions, selector nesting, and other cool things. This makes CSS code very easy to manage, especially in large projects.

For a simple example, here's a Sass snippet that uses CSS 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 to using CSS preprocessors is that they need to be compiled into real CSS code, but if you have decided to use a build script in your project, then this is no longer an issue you should be bothered with.

17, Autoprefixers

Adding a prefix to each browser is the most annoying problem with writing CSS code. They are inconsistent, you can never be precise which one you need, and if you really fit one by one and put them all in the style sheet, you will find this a nightmare.

Thank God, there are a lot of tools that can help you with this process automatically, and even let you specify the browser you need to support:

Online Tools: Autoprefixer Text Editor Plugin - Sublime Text, Atom Library - Autoprefixer

18, use streamlined code in the project

In order to improve the page load speed of the website or app, we need to always use the streamlined code. The streamlined version of the code will remove the blank and duplicate parts, which will reduce the file size. Of course, then your CSS code will become Very difficult to read, so it's best to always provide a .min lite version and a regular development version.

There are many different ways to streamline CSS code:

Online Tools - CSS Minifier, CSS Compressor Text Editing Plugin - Sublime Text, Atom Library - Minfiy, CSSO and CSSNano

Depending on your workflow, you can choose one of the above options, but it is recommended that you always automate this process in some way.

19, Can I Use

There are still many inconsistent compatibility issues in different browsers. Use caniuse or other similar services to check if the property you are using is widely supported, whether you need to add a prefix, or whether there will be a bug on a platform.

Just checking if it is still not enough, you still need to test whether the layout will crash for no reason. It is also very helpful to fully understand the browsers that users often use, so you can see that good support is very important.

20, Validate

It's important to verify that CSS code doesn't validate HTML or JavaScript code, but it's helpful to run your code on a CSS validator. It will prompt you if you've written a mistake or bad code, and even give some more pertinent It is recommended to help you improve your code.


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.