Margin is one of the most commonly used attributes in CSS la S. However, if it is not used properly, too much junk code is often generated, increasing the size of our encoding. Today we will introduce a small example of code optimization. Through this example, we hope you can realize that there are many ways to optimize code.
Check the XHTML code:
The code is as follows: |
Copy code |
<Div id = "main"> <Div id = "body1"> <Div id = "content1"> </Div> </Div> <Div id = "body2"> </Div> <Div>
|
See the following CSS code: (not optimized)
The code is as follows: |
Copy code |
# Main { Margin: 5px 0px 5px 0px; } # Body1 { Margin: 12px 0px 10px 0px; } # Content { Margin: 8px 0px 2px 0px; } # Body2 { Margin: 10px 0px 15px 0px; }
|
I personally do not use Dreamweaver for development. In my opinion, the CSS set with Dreamweaver should belong to this category. It is not optimized and many codes are redundant, because software is software after all, there is no way to think about it. We optimized the above CSS.
See the following optimized CSS code:
The code is as follows: |
Copy code |
# Main {} # Body1 { Margin-top: 17px; } # Content { Margin: 8px 0px 2px 0px; } # Body2 { Margin: 20px 0px; }
|
Let's analyze the optimization ideas. First, # main {margin: 5px 0px 5px 0px;} is unnecessary, it defines the top and bottom margins of the entire page (which needs to be written in this way under certain circumstances ). We can also define the top margin of # body1 and the bottom margin of # body2, so we have # body1 {margin-top: 17px;} and # body2 {margin: 20px 0px;} (the upper and lower margins of # body2 are 20px and the left and right margins are 0px, which is also an abbreviated method .) Similarly, we can omit the bottom margin of # body1 and define the top margin at the # content layer. In addition, you need to first figure out the nested relationship of the layer, otherwise, it is easy for you to think clearly.