In this article, we would like to share with you a collection of 20 useful rules and best practices recommended by major CSS websites. Some are for CSS beginners, and some are advanced. I hope everyone can learn useful knowledge from this article. Okay, let’s begin. 1. Pay attention to margin collapse Unlike most other properties, top and bottom vertical margins collapse when present together. This means that when the bottom edge of one element touches the top edge of another element, only the larger of the two margin values will be retained. For example: 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; } The top and bottom spacing between the red and blue squares is 40px, not 70px. There are many ways to solve the problem of margin collapse. For beginners, the simplest way is to use margin in only one direction for all elements. For example, we use margin-bottom for all top and bottom margins. 2. Use flex for layout There is a reason why flex layout appears. Although float and inline-block can achieve many layout effects, they are essentially tools for the layout of text and block elements, rather than for the entire web page. Flex makes it easy to create layouts the way we expect. Flex has a set of properties for "flex containers" and a set of properties for "flex items". Once you learn them, making any responsive layout is a piece of cake. Currently, the latest versions of various browsers have no problems supporting flex, so you should use flex layout more often. .container { display: flex; } 3. Reset the CSS style of the element Although things have improved a lot over the years, there are still large differences between browsers in the default styles of various elements. The best way to solve this problem is to set a common CSS Reset code for all elements at the beginning of the CSS, so that you are laying out without any default inner and outer margins, so the effect is uniform. There are already mature CSS code libraries on the Internet that solve browser inconsistencies for us, such as normalize.css, minireset, and ress. You can reference them in your project. If you don’t want to use a third-party library, you can use the following styles for a very basic CSS reset: * { margin: 0; padding: 0; box-sizing: border-box; } The above code may seem a bit overbearing, as it sets the inner and outer margins of all elements to 0. However, without the influence of these default inner and outer margins, the subsequent CSS settings will be much easier. At the same time, box-sizing: border-box is also a great setting, which we will introduce next. 4. Set all elements to Border-box Most beginners are not aware of the box-sizing property, but it is actually very important. The box-sizing property has two values:
By setting all elements to border-box, you can more easily resize the elements without having to worry about padding or border values stretching the elements or causing them to wrap. 5. Use pictures as background When adding images to a page, especially when you need the images to be responsive, it is best to use the background attribute to include the image instead of the <img> tag. This may seem more complicated to use with images, but it actually makes styling your images much easier. With background-size, background-position and other properties, it is convenient to keep or change the original size and aspect ratio of the image. For example <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 downside of using images in the background is that the web accessibility of the page will be slightly affected because screen readers and search engines will not be able to correctly retrieve the image. This problem can be solved by using the CSS object-fit property. So far, all browsers except IE can use object-fit. 6. Better table borders Tables in HTML have always been ugly. They are difficult to make responsive, and generally hard to restyle. For example, if you want to add a simple border to a table and its cells, the most likely results would be: As you can see, there are a lot of repeated borders, which doesn’t look very nice. Here’s a quick way to remove all double borders: border-collapse: collapse. Just set this property and the table borders will look much better: 7. More friendly comments CSS may not be a programming language, but its code still needs to be documented. Adding some simple comments can help you categorize and differentiate the code, making it easier for you and your colleagues to maintain it later. For large area divisions or important components, the following annotation style can be used: /*--------------- #Header ---------------*/ header { } header nav { } /*--------------- #Slideshow ---------------*/ .slideshow { } For details and less important styles, you can use single-line comments: /* Footer Buttons */ .footer button { } .footer button:hover { } Also, remember that there are no // comments in CSS, only /**/ comments: /* correct*/ p { padding: 15px; /*border: 1px solid #222;*/ } /* mistake*/ p { padding: 15px; // border: 1px solid #222; } 8. Hyphen naming When a class or ID contains multiple words, a hyphen (-) should be used. CSS is case-insensitive, so camelCase naming cannot be used. Similarly, the use of underscores in naming is not recommended in CSS. /* correct*/ .footer-column-left { } /* mistake*/ .footerColumnLeft { } .footer_column_left { } When it comes to naming, you can also consider BEM, which follows a set of principles that provide a component-based development approach that increases consistency. 9. Don’t repeat settings Most CSS properties are inherited from the element one level up in the DOM tree, hence the name Cascading Style Sheets. Take the font property for example - it's always inherited from the parent, you don't have to set it individually for every element on the page. Simply add the font styles you want to set to the <html> or <body> element and let them automatically inherit downwards. html { font: normal 16px/1.4 sans-serif; } Then we can change the text styles of all the pages at once. Of course, not all properties in CSS are inherited, and for these properties we still need to set them individually on each element. 10. Use the transform property to create animations It is best to use the transform() function to create element displacement or size animation, and try not to directly change the element's width, height, and left/top/bottom/right attribute values. In the following example, we add a left-to-right animation to the .ball element. It is recommended to use the transform: translateX() function instead of the left attribute. .ball { left: 50px; transition: 0.4s ease-out; } /* Not recommended*/ .ball.slide-out { left: 500px; } /* suggestion*/ .ball.slide-out { transform: translateX(450px); } Transform and all its functions (translate, rotate, scale, etc.) have almost no browser compatibility issues and can be used at will. 11. Don’t DIY, use libraries The CSS community is huge, with new codebases appearing all the time. They have various uses, from tiny snippets to whole frameworks for building responsive applications. Most of them are also open source. Next time you’re faced with a CSS problem, before you try to solve it with all your might, check if there’s already a solution available on Github or Codepen. 12. Keep selector weights low Not all CSS selectors are created equal. When I first learned CSS, I always thought that a selector overrides everything above it. However, this is not the case, as we illustrate in the following example: HTML <a href='#' id='blue-btn' class="active">Button</a> CSS a{ color: #fff; padding: 15px; } a#blue-btn { background-color: blue; } a.active { background-color: red; } We want the styles set in the .active class to take effect and turn the button red. But it won’t work because the button has an ID selector on it which also sets background-color , and the ID selector has a higher specificity, so the button’s color is blue. The weight size specifications of the selector are as follows: ID (#id) > Class (.class) > Type (e.g. header) Weights also add up, so a#button.active has a higher weight than a#button. Using a high-priority selector at the beginning will cause you to constantly use higher-priority selectors in subsequent maintenance, and eventually choose to use !important. This is highly not recommended. The specific reasons will be discussed next. 13. Don’t use !important Seriously, don't use !important. It may seem like a quick fix now, but it may end up requiring a significant rewrite. Instead, we should take the time to find why the CSS selector isn’t working and change it. The only place you can use !important is when you want to override inline styles in the HTML, but inline styles are also a bad habit and should be avoided as much as possible. 14. Use text-transform to convert letters to uppercase This article is applicable to English environment, not Chinese In HTML, you can write a word in all uppercase letters to emphasize it. for example: <h3>Employees MUST wear a helmet!</h3> If you need to convert a certain text to all uppercase, we can write it normally in HTML and then convert it using CSS. This keeps the context consistent. <div class="movie-poster">Star Wars: The Force Awakens</div> .movie-poster { text-transform:uppercase; } 15.Em, Rem and px Which unit should I use to set the size of elements and text, em, rem, or px? There has always been a lot of debate. The truth is, all three options are viable and all have their pros and cons. There is no definitive answer as to which unit should be used in which project. Developers may use different units due to different habits and project requirements. However, while there are no hard and fast rules, there are some things to keep in mind for each unit:
Most importantly, don’t be afraid to experiment, try them all and see what works best. Sometimes, em and rem can save a lot of work, especially when building responsive pages. 16. Use a preprocessor for large projects You’ve definitely heard of them — Sass, Less, PostCSS, Stylus. Preprocessors are the future of CSS. They provide features like variables, CSS functions, selector nesting, and many other cool features that make CSS code more manageable, especially in large projects. As a simple example, here is a snippet of SASS code that uses some 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 preprocessors is that they still need to be compiled into regular CSS. The custom properties introduced by CSS are true preprocessing. 17. Use AutoPrefixer to achieve better compatibility Browser prefixes are one of the most annoying things about CSS. The prefix required for each property is inconsistent, and you never know which one you need. If you really have to add it manually one by one in your stylesheet, it will undoubtedly be a boring nightmare. Thankfully, there are tools that can automatically add browser prefixes for us, and even decide which browsers we need to support: Online tool: Autoprefixer Text editor plugins: Sublime Text, Atom Codebase: Autoprefixer (PostCSS) 18. Compress CSS files To improve loading speed and page load of your website and applications, you should use compressed assets. The compressed version of the file will remove all whitespace and duplication, thus reducing the overall file size. Of course, this process also renders your stylesheet completely unreadable, so use the .min version in production while keeping the regular version for development. There are many different ways to compress CSS code: Online tools: CSS Minifier, CSS Compressor Text editor plugins: Sublime Text, Atom Atom repositories: Minfiy (PHP), CSSO, CSSNano (PostCSS, Grunt, Gulp) Depending on your workflow, you can use either of the above approaches. 19. Caniuse There are still many compatibility inconsistencies among web browsers regarding CSS properties. Use caniuse to check if the properties you use are widely supported? Is a prefix required? Or is there anything I need to be careful about when using it in a certain browser? With caniuse you will be more comfortable writing CSS. 20. Verification Validating your CSS may not be as important as validating your HTML or JavaScript code, but it’s still very useful to run your code through a tool. It will tell you if you made any mistakes, warn about incorrect usage, and give you tips for improving your code. Just like with Zip and Autoprefixer, there are free tools you can take advantage of: Online tools: W3 Validator, CSS Lint The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM. |
>>: JavaScript to achieve floor effect
Native js realizes the carousel effect (seamless ...
First, let me briefly introduce what MySQL is; In...
1 Background Recently, I have been studying how t...
MySQL is divided into Community Edition (Communit...
This article example shares the specific code of ...
Step 1: Use Notepad to open the "my.ini"...
The emergence of jQuery has greatly improved our ...
download: Step 1: Open the website (enter the off...
Recently, new projects have used springcloud and ...
Unlike other types of design, web design has been ...
Table of contents Start by clicking the input box...
DPlayer.js video player plug-in is easy to use Ma...
1. Command Introduction The gzip (GNU zip) comman...
XML/HTML CodeCopy content to clipboard <!DOCTY...
1. Make sure the network connection method is bri...