1. Introduction
There are a few days to the National Day Mid-Autumn Festival, is about to have a holiday, I wish you a happy holiday first! I’ve written javascript advice and tips before, so today let’s talk about CSS! When it comes to CSS, every web page is inseparable from CSS, but for CSS, the idea of many developers is that CSS can only be used for layout and rendering, other details or optimization, do not need to think about. But I think CSS is not just the layout of the page is finished, but also need to consider a lot of details have optimization, but not as simple as you think, in the study, if you find what skills or optimization points, I will learn to use! So today, let’s share my summary of CSS writing advice and performance optimization some questions! Hopefully this will give you a new understanding of the magic of CSS, of course, if you have any other suggestions. Welcome advice!
2. CSS rendering rules
First, the rules of CSS rendering, as you probably know, is to render from right to left! The following chestnuts
.nav h3 a{font-size: 14px; }Copy the code
The rendering process looks like this: first find all a’s, look for H3 along the parent element of A, and then look for.nav along h3. If a node matching the matching rule is found, it is added to the result set. If no match is found for the root element HTML, the path is no longer traversed and the search is repeated starting with the next A (as long as there are more than one right-most node on the page with a). Reference: CSS selectors match rules from right to left
3. Do not nest more than three levels
In general, the nesting level of elements should not exceed 3 levels. Excessive nesting will lead to bloated, heavy, and complex code. Causes the CSS file volume to become large, causes the performance waste, affects the rendering speed! It also relies too much on HTML document structure. Such CSS style, maintenance, extreme trouble, if you want to change the style later, may have to use! Important coverage.
4. Style resets
I’m on the fence about this for now, because looking at the articles on the Internet, some people are in favor of using style resets, and some people are not. In my own case, I have used style reset, but it is a relatively simple summary, the code is as follows!
body,dl,dd,h1,h2,h3,h4,h5,h6,p,form,ol,ul {
margin: 0;
padding: 0;
}
h1, h2, h3, h4, h5, h6 {
font-weight: normal;
}
ol, ul {
list-style: none;
}
h1{
font-size: 24px;
}
h2{
font-size: 20px;
}
h3{
font-size: 18px;
}
h4 {
font-size: 16px;
}
h5{
font-size: 14px;
}
h6{
font-size: 12px;
}
Copy the code
5. Style level
First, the CSS style levels are organized as follows
! Important > Inline Style > ID Style > Class Style > Tag Name style. And one thing to mention is that the combination selectors use values stack. For example, id weight is 100, class is 10, tag name is 1! Div. Test-class = 11, div#test = 101
Let’s say I have a div
<div id="test" class="test-class" style="color:green;"></div>
Copy the code
So in terms of style weights
div {color: red ! improtant;
6. The inline – block margin
No explanation, look at the picture
Margin and padding are all 0 for the above p elements, but there is also margin. There are two solutions to this
1. Delete the blank space before the code
All blank lines before elements with display:inline-block are removed, as shown below
2. Set the parent element’s font-size to 0
7. Set width and height for the image
Img recommends setting width and height if the page has an IMG tag. The purpose is to ensure that the layout is not messy when the image cannot be loaded due to network speed difference or other reasons.
Here’s chestnuts, a very common layout.
But in case of any situation, the image load can not come out, the recommended way is the first, show a default picture, even if not show the default picture, also let the picture has a placeholder role, ensure that the layout will not be disorderly!
If the image does not load and img does not set width and height, it will look like this.
Set width and height in the img tag attribute. 2. Mobile station, it is recommended to use CSS to set the width and height of img, because mobile station to do adaptation, in the property of the setting of width and height is not flexible, such as rem layout, in the property there can not set the width and height. 3. If the image is not fixed, but has a max-width and max-height, then it is recommended to set width and height in the parent element of IMG. Img sets max-width and max-height based on the width and height of the parent element.
8. Any element is vertically centered
This is just the picture, not the explanation
8-1.table-cell
8-2.flex
8-3. The position, the transform
8-4. The position and margin
This is not recommended because the width and height of.div2 must be set otherwise it will be 100%. For example, set top:0; bottom:0; Effects and Settings Height :100%; It’s the same thing. If you want to avoid it, you have to set the height.
9. Image preloading
I’m not talking about lazy loading. First of all, according to my personal understanding of popular science, the difference between lazy loading and preloading.
Lazy loading: When the page loads, some content is loaded first (usually the first screen content) and the rest is loaded when it needs to be loaded!
Preloading: When a page is loaded, a portion of the content (usually the first screen content) is loaded first, and the rest of the content is loaded after the first part of the content (usually the first screen content) is loaded.
Both ways, in order to reduce the user to enter the site, see the content of the first screen faster!
Add the #preloader element to the HTML to preload the image to the off-screen background using the CSS background property. The browser uses preloaded (cached) images during rendering when they are called elsewhere on the Web page, as long as their paths remain the same. Simple, efficient, and doesn’t require any JavaScript.
#preloader {*/ Background: url(image1.jpg) no-repeat,url(image2.jpg) no-repeat,url(image3.jpg) no-repeat; width: 0px; height: 0px; display: inline; }Copy the code
There is a problem with this, however, because #preloader preloads images along with the rest of the content on the page, increasing the overall load time of the page. So you need to use JS control
function preloader(urlArr,obj) {
var bgText=' ';
for(var i=0,len=urlArr.length; i<len; i++){bgText+='url('+urlArr[i]+') no-repeat,';
}
obj.style.background=bgText.substr(0,bgText.length-1);
}
window.onload = function() {
preloader(['image1.jpg'.'image2.jpg'.'image3.jpg'],document.getElementById('preloader'));
}Copy the code
The principle is very simple, let the first screen image load, and then load the other images. # PreLoader loads the required images by setting the background image. Then, when the page needs to load the images, it takes the images directly from the cache. No HTTP request is required to load the images.
10. Use the * wildcard with caution
The following two styles are often used when making web pages to eliminate the default layout of the TAB and the rendering of the same TAB by different browsers.
* {margin: 0; Padding: 0; }Copy the code
The above method has less code, but poor performance, because when rendering, you have to match all the elements on the page! Many basic styles do not have margin and padding elements, such as div, li, etc. It’s all matched. It’s totally unnecessary! Let’s do it the other way.
Body, dl, dd, h1, h2, h3, h4, h5, and h6, p, form, ol, ul {margin: 0; Padding: 0; }Copy the code
This way, the code a little more, but the performance is better than the way above, at the time of rendering, only match body, dl, dd, h1, h2, h3, h4, h5, and h6, p, form, ol, ul here elements, these elements with margin and padding, need to reset! Here’s another example:
.test * {color: red; }Copy the code
Matches all of the elements in the document, and then each of the elements of class test is matched up to the root node of the document
.test a {color: red; }Copy the code
Matches all the elements of a in the document, then each of the elements of class test is matched up to the root node of the document
It is self-evident which of the two is better, so it is recommended to avoid wildcard selectors during development.
11. Merge and compress CSS
There’s nothing to explain here, just compress and merge CSS.
First compress CSS, in addition to using tools such as gulp, Webpack and so on to compress the code, remove the whitespaces and newlines. Another suggestion is property shorthand.
Such as
margin-top:0;
margin-right:10px;
margin-bottom:10px;
margin-left:10px;
background-image: url('test.jpg');
background-position: top center;
background-repeat: no-repeat;
border-width:1px;
border-style:solid;
border-color:# 000;
color:#0099FF;
Copy the code
I could replace it with this one down here
margin:0 10px 10px 10px;
background: url('test.jpg') no-repeat top center;
border:1px solid # 000;
color:#09F;
Copy the code
When it comes to merging, I have a few suggestions based on my own development habits: 1. Merge common styles, such as the header, bottom, and sidebar of the project, which are generally common. These can be written in a common style sheet, such as main.css. 2. Main. CSS is used for every page, and reset. CSS is also used for every page, so it is recommended to merge main. CSS and reset. CSS into one file and introduce it to the page! Reduce requests! 3. Each page is styled as an independent file. For example, the home page is index. CSS. The style for the product list page is product-list.css. Then index. CSS is only introduced on the home page, and not on other pages, because it is a waste of request resources! The same is true for other pages! CSS, product-list. CSS and other page styles are kept in a separate file, not to be merged!
12. CSS introduced in head
The browser does not render the entire page until all of the stylesheets are loaded. Until then, the browser does not render anything in the page. The page remains blank. That’s why you put a stylesheet on your head. If you put it at the bottom of the HTML page, the render will not only wait for the stylesheet to load, but also wait for the HTML content to load, so the user will see the page later.
13. Avoid @import
CSS style files can be imported in two ways, one is the link element and the other is @import. My advice here is to avoid @import. Because @import affects the browser’s parallel download, it adds an extra delay when the page loads, adding an extra round trip. And multiple @imports may cause the download order to get out of order. For example, a CSS file index.css contains the following: @import URL (“reset.css”). The browser must download, parse, and execute index.css before downloading, parsing, and executing the second file reset.css. The simple solution is to use instead of @import.
14. How to write code from PSD files
Received renderings, do not need to urgently figure, first look at the PSD file. Think about the layout, which modules can be made into common modules, how the modules should be named, write style, etc. When we get the PSD from the designer, first don’t rush to write CSS code, first analyze the whole page, first think about the following: (1) analyze what page is the module is common, common utility module has the head, the bottom of the menu bar, suspended button, etc. (2) what style analysis module, extract the common patterns, public styles including the state of the style, such as buttons, input fields, drop-down box public selected, such as the style of the disabled and so on.
15. Processing scheme of small ICONS
A website is sure to have a lot of small ICONS, for these small ICONS, the current solution has two, cssSprite, font icon, to turn the image into Base64. Let’s compare these two ways! CssSprite: Combine all the icon images into a PNG image, using at, set the width and height of each node, and add bacgroud-position. Display the required icon in the way of background image. If a website has 20 ICONS, then it needs to request 20 times. Using cssSprite, it only needs to request once, greatly reducing HTTP requests. The disadvantage is that management is not flexible, if you need to add an icon, all need to change the merged image of the source file, icon positioning should also be standardized, otherwise easy to interfere with the positioning between pictures! Font icon: the simple understanding is to treat all ICONS as a font! This way you don’t have to ask for pictures. Generally use class to define the icon, to replace the icon, only need to change the style name, convenient management, clear meaning, flexible zoom in and out, and will not cause distortion. But only monochrome images are supported. Base64: Another solution is to convert small icon images to Base64 encoding. This way, you don’t need to request the image. The base64 encoding is directly integrated into js or CSS, which can prevent the image 404 error caused by some relative paths, or the image is greatly deleted. But finding a way will generate a whole bunch of Base64 encodings. Generally, images below 8K are converted to Base64 encoding. If you convert a 50K image to a Base64 encoding, you will generate a Base64 encoding of more than 65,000 characters, which is nearly 70K in character size! The suggestion is: Only convert to Base64 encoding for images below 8K.
16. Do not nest or write tags before ID selectors
1.ID is unique on the page and has a large weight. Nesting (.content #test) is a waste of performance. And write more code that doesn’t make sense! Although this is a sentence, but still some people make such a mistake! 2. In addition to nesting, no tags or other selectors are required before the ID. So let’s say div#test or test#test. Both of these approaches are completely redundant because the ID is unique on the page. Anything in front of it is superfluous!
17. Encapsulate common styles into common styles
Extract long segments of the same style as common style, such as the common clear float, single line out of the ellipsis, multi line out of the ellipsis, etc.
The following chestnuts
/* Beyond the ellipsis */ /*<p class='text-ellipsis'></p>*/ .text-ellipsis{ overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } /* Clear float */ /*<div class='clearfix'></div>*/
.clearfix:after {
display: block;
content: ' ';
clear: both;
height:0;
}
Copy the code
18. Optimization of CSS3 animation
In my previous article (Summary of Mobile Web Development Issues and Optimization), I have also written some optimization suggestions about this. The two suggestions mentioned above are: 1. Use transform and opacity instead of left and top to animate CSS3 animations or transitions. 2. If animations and transitions can be handled in CSS3, do not use JS. If it is complex animation can use CSS3 + JS (or HTML5 + CSS3 + JS) with development, the effect is only unexpected, nothing can be done.
The following adds: animation should not be too much, especially mobile website, otherwise there will be performance problems, such as CPU is occupied all at once, frame drop and so on. Also, hardware acceleration for every element is not recommended.
CSS Animation Performance optimization CSS3 Animation Performance optimization CSS Animation hardware accelerated Web Animation
19. Body sets the minimum width
This is in the PC station will appear the problem, should everyone know. Below briefly say! For example, in the following example, a website, the page content width is 1200px. It looks normal. Nothing special, you know
If this happens, make the page window smaller. Below 1200px, a scroll bar appears on the page, and drag the scroll bar to the far right
In this way, it is not found that the top of the picture and the background is part of the fault! The solution is as simple as adding min-width to the body. The value is the value of the page width. body{min-width:1200px; }
Repeat the previous step, no matter how you change the size of the browser window, it will be fine
This problem occurs because, for example, when the window is reduced to 900px, it is less than 1200px of the content width. The horizontal scroll bar appears, but the body is 900px wide. At this point, if any element (such as the gray area of the image and the pink image) is set to 100% relative to the body width, the actual width of the element is 900px. So there will be a disconnect of those vision! The solution is to add min-width to the body. Make the body at least as wide as the content!
Nodule 20.
So much for my summary of CSS writing advice and performance optimization. CSS is definitely not a language that you just need to use, or you just need to use CSS to get your layout right. My impression of CSS is that it’s easy to get started, but if you want to use CSS well, you still need to spend time studying it. CSS or CSS3, can optimize things there are many, with good CSS or CSS3 can write a lot less JS code, to make things is also very magic, we still have to continue to learn the knowledge! If you think my article is not good, write wrong, welcome to correct. If you have any other suggestions, welcome to give directions, let us communicate with each other, learn from each other, progress together! Finally, I wish everyone a happy holiday!
— — — — — — — — — — — — — — — — — — — — — — — — — gorgeous line — — — — — — — — — — — — — — — — — — — — want to know more, pay attention to focus on my WeChat public number: waiting for book cabinet