Relative/absolute in CSS

Source: Internet
Author: User
Tags comparison
The absolute attribute works well with the left/top/right/bottom attribute. This feature is so obvious and strong that it may make page reconfigurator "captured" by this feature and lost.
The description at a glance may be hard to understand. Let's take a simple example:
A girl with a nice face and a super-good figure put on her super PP clothes, it was so brilliant and charming. For The Bachelors of us who have been trapped in the home courtyard all the year round, this kind of beauty is so charming, so much our energy is concentrated on the beauty of the fallen geese, ignoring other things, such as intellectual, kind, and virtuous. It is easy to think of this girl later. The first reaction is "beauty". As for others, it is no longer important to be so beautiful.
This principle is reflected on the web. We can easily preemptively think that the value of absolute is determined by the left/top attribute. If the statement is not rigorous, it is estimated that more than 90% of the general layout's absolute attributes are currently used for positioning. Well, let's look back at some common absolute la s to see how other attributes can achieve the same layout effect. Since the absolute attribute is used for locating, we only need to use other attributes for locating. At this point, we naturally think of another lower-key and all-powerful positioning attribute margin in CSS. The first two examples below use margin to replace absolute and related attributes.
Jingdong Mall homepage price positioning
Take a price chart on the homepage of Jingdong Mall as an example. See the screenshot below:
When I look at the code implementation with a small bug, it turns out to be an absolute positioning + positioning attribute: // zxx: The nickname of firebug
If I implement it, the absolute attribute will not be used, and the margin will be used to implement a layout with higher scalability and fault tolerance.

In any case, let's first look at the comparison and implementation effect,

The code is as follows:

<Div class = "w">
<P> & nbsp; </p>
<Div id = "newpros"> <div class = "mt"> <Div id = "madding-1" class = "mc list-h">
<Div class = "tabcon list-h">
<Dl>
<Dt class = "p-img">
<A href = "#"> </a>
<Div class = "p-price"> ¥999.00 </div>
</Dt>
<Dd class = "p-name">
<A href = "#"> LG GD580 3G mobile phone 3 million pixels 999 back 100 yuan coupon! </A>
</Dd>
</Dl>
</Div>
</Div>
   
<P> & nbsp; </p>
<Div id = "newpros"> <div class = "mt"> <Div id = "madding-1" class = "mc list-h">
<Div class = "tabcon list-h">
<Dl>
<Dt class = "p-img">
<A href = "#"> </a>
<Div class = "new-price-x"> <span class = "new-price"> ¥999.00 </span> </div>
</Dt>
<Dd class = "p-name">
<A href = "#"> LG GD580 3G mobile phone 3 million pixels 999 back 100 yuan coupon! </A>
</Dd>
</Dl>
</Div>
</Div>
<P> & nbsp; </p>
<Button id = "btnWidth"> change width </button> <button id = "btnRelative"> static parent tag </button>
</Div>

<Script>
Var oDl = document. getElementsByTagName ("dl"), lDl = oDl. length,
ODt = document. getElementsByTagName ("dt"), lDt = oDt. length;
  
Document. getElementById ("btnWidth"). onclick = function (){
For (var I = 0; I <lDl; I + = 1 ){
ODl [I]. style. width = "470px ";
  }
};
Document. getElementById ("btnRelative"). onclick = function (){
For (var I = 0; I <lDt; I + = 1 ){
ODt [I]. style. position = "static ";
  }
};
</Script>

The following figure shows a screenshot of the upper and lower implementation modes in the IE 7 browser (default ):

It can be seen that the use of margin can achieve the same effect as the absolute layout, and the CSS attribute usage is halved. More importantly, the layout's scalability and fault tolerance are greatly enhanced.
There are two buttons at the bottom of the demo page to test the layout scalability and fault tolerance, as shown in the following figure. The first button is to change the label width, and the second button is to change the position attribute of the parent label to static:
After we click the first button to change the width of the dl parent tag, the value of the absolute tag is far away from the image, the price of the orange-red background marked with margin remains firm at the original position, as shown in the following figure:
After you click the second button to change the position attribute of the parent tag to static, the result is that the price of the absolute location with absolute is not bound, and you can directly go to the lower right corner of the browser window, the positioning of margin has no effect (as shown in the following figure, captured from Firefox3.6 ):
From the two simple tests above, we can see the differences between the two implementation methods in terms of scalability and fault tolerance.
The following is a brief introduction to the implementation of related la S. The following is the code of the original absolute implementation:
HTML section:
	
  
The code is as follows: Copy code
<Dl> <dt class = "p-img"> <a href = "#">  </a> <div class = "p-price"> ¥999.00 </div> </dt> <dd class = "p-name"> <a href =" # "> LG GD580 3G mobile phone 3 million pixel 999 back 100 yuan coupon! </A> </dd> </dl>
The core style of the class name "p-price" label is as follows:
	
  
The code is as follows:
. P-price {position: absolute; bottom: 10px; right: 50px;
......
The implementation of Jingdong Mall is quite satisfactory. If you want to find a location with coverage effect, using absolute positioning is estimated to be the first choice for most page reconstruction personnel. However, the word "absolute" in absolute positioning means that its performance in scalability is limited. If we have higher requirements, we can use a margin layout with less CSS code and higher scalability.
The implementation code is as follows:
First, you need to add a horizontal block label to the HTML part (in fact, you do not need to add it, as long as the tag block outside the img can be horizontally displayed ), so that the price and image will not be displayed in a line box, and the div label outside the price is changed to the label of the inline horizontal element to facilitate inline-block, so the final HTML code is as follows:
	
  
The code is as follows: Copy code
<Dl> <dt class = "p-img"> <a href = "#">  </a> <div class = "new-price-x"> <span class = "new-price"> ¥999.00 </span> </div> </dt> <dd class = "p-name"> <a href = "#"> LG GD580 3G mobile phones: 3 million pixels, 999 yuan coupons! </A> </dd> </dl>
The core CSS code is as follows:
	
  
The code is as follows:
. New-price-x {margin:-28px 0 0 74px;}. new-price {display: inline-block ;......}
Taobao homepage example
Next, let's look at another example, that is, the scrolling playback effect of the Taobao homepage. It uses absolute to locate and implement rolling switching between the top and bottom by changing the top attribute values, as shown in the figure below:
Slide rolling Zhang Xinxu-Xin space-Xin Sheng live "height =" 379 "alt =" Taobao homepage absolute slides rolling Zhang Xinxu-Xin space-Xin Sheng live "width =" 553" src = "http://filesimg.111cn.net/2012/02/21/20120221022312939.png" _ fcksavedurl = "http://filesimg.111cn.net/2012/02/21/20120221022312939.png"/>
In fact, you can use the margin-top attribute to replace the relative + absolute + top attribute combination.
You can click here: the scroll playback demo under the Taobao homepage margin
Use the bug to check the positioning attribute of the demo page. Ah, it's margin-top, as shown in the screenshot below:
As far as the effect is concerned, the switching between margin-top and absolute positioning is the same, with the advantage of saving a little bit of CSS code. However, compared with the absolute animation switching, the changes in the margin-top value will produce a stronger reflux (reflow). In terms of performance, it is lower than the absolute attribute.
Which one is used depends on your choice.
Sina Weibo example
Finally, take the main navigation example on the Sina Weibo page.
First, let's see why Sina Weibo's main navigation should use absolute positioning. I think the main reason may be a translucent solid background.

The internet browser uses the filter to implement the opacity effect. However, the translucent effect of the opacity attribute will not only affect the current element, but also the translucent effect of all sub-elements. At this time, if the element in the navigation is placed inside the translucent div, it is easy to hide. Therefore, the translucent background layer is not a parent-child relationship with the navigation content layer, but a sibling relationship. The navigation content covers the translucent background, which avoids the danger of the navigation content being translucent.
Coverage and positioning are generally inseparable from the absolute attribute. Therefore, Sina Weibo's main navigation uses absolute positioning. However, I must praise the absolute positioning here, because it is rare that the absolute here is mainly used to make use of the destructiveness of the absolute attribute (the high width occupies the space of 0 ), instead of using its positioning (with the help of the positioning of left/top and other attributes ).
I don't want to talk about how to use the destructive properties of absolute to achieve adaptive layout. If you have weibo, use a small bug to check whether you have registered Weibo.
In terms of usage, apart from the inexplicable top/right attribute, it is still good. However, is absolute positioning required? Do I have to use two parallel labels to stagger and locate the compatibility translucent solid color effect? Cannot the parent-child relationship work? There is an idiom called "keep up with the times". If it was just a few years ago, it might have to be done like this. But now, what is absolute positioning? Overlapping? Computing? Nothing messy. If there is no translucent effect, the same effect can be achieved.
Similarly, I made a demo about the alternative method here. You can click here: the demo is implemented without absolute in the main navigation bar of Sina Weibo.
Using the opacity attribute or the IE filter translucent filter will make the child element semi-transparent. In fact, there are better implementation methods for translucent solid background. The following is the CSS code for the replacement implementation method of the demo page:
	
  
The code is as follows: Copy code
. Newheader. menu_c {background-color: rgba (0, 0, 0 ,. 25); filter: progid: DXImageTransform. microsoft. gradient (startColorStr = #40000000, endColorStr = #40000000 );}
Modern browsers use CSS3 rgba for translucent background color, while IE browsers use gradient filters for translucent.
In HTML, the original absolutely positioned translucent div layer is directly deleted, and the related relative attributes can also be removed. The HTML structure becomes simple, hierarchical, and easier to maintain.
For the translucent background color for compatibility, refer to my previous article "RGBA color and compatibility translucent background color. So the specific usage and details will not be discussed here. The following figure shows the comparison of the effects of the two translucent backgrounds:
2. absolute can be fought by one person
Without the left/top/right/bottom attribute in the CSS world, the potential of absolute is estimated to be much deeper.

We need to realize that the position: absolute element of an application is actually a very common element. I feel that the difference between it and the float: left is only the lack of width. To illustrate this point, I made a very simple de

The code is as follows:

CSS code:
. Test_box {padding: 10px; background-color: # f0f3f9 ;}
. Test_img {float: left;} HTML code:
<Div class = "test_box">

This time, I had a hard time rehearsing for the New Year's Gala in December 31. I believe how much sweat can bring me many surprises! When it comes to surprises, I suddenly think of Zhang Machi's line: What is a TM surprise for you to translate? It's really cool and domineering... (from Zhang Hanyun's Sina blog)
</Div>
<Div class = "test_btn"> <button id = "testBtn"> changed to absolute </button> </div> JS code:
Var oTestImg = document. getElementById ("testImg"), oTestBtn = document. getElementById ("testBtn ");

OTestBtn. onclick = function (){
If (this. innerHTML = "change to absolute "){
OTestImg. style. position = "absolute ";
This. innerHTML = "remove absolute ";
} Else {
OTestImg. style. position = "static ";
This. innerHTML = "changed to absolute ";
    }
};

This demo is shown in the figure below by default. You can see the collapse caused by the missing floating height:

After clicking the motioned button, you can find that the image is still in that position, still so quiet and elegant. The only difference is that some of the text is below it (the width is missing ).
It can be seen that the absolute attribute is just a common attribute and is close to the float: left attribute. One is the demon that falls into the mortal world, and the other is the demon in the sky. Therefore, when we use absolute in a general layout, we only need to set position: absolute. As for left/top and other items, they are all floating clouds, and positioning and other items are treated as common elements, the use of margin for positioning is equally helpful.
III. Relationship between absolute and left/top attributes
The element that simply applies the absolute attribute is a common element, just like the beautiful girl warrior before the transformation. Left/top and other attributes are transformed things and wings of the devil's absolute element. Once the left/top attribute is applied to the absolute element, it has the flying ability to fly freely to the sky. If there is no limit on the relative attribute, it will always fly to the edge of the Sky (browser window), and has a very clear direction.
4. The body tag is the free sky of the absolute element.
Let's adjust the first poem:
Life is precious,
Love price is higher.
If it is free,
Both can be discarded.
Know the beautiful girl warrior, know the hero "Shui Bingyue (Yue hares)", because of the ox cross, so in order to protect the Earth and protect the future and fight. Do you know "Naruto"? If you want to restrict Naruto to Huoying village, help the old lady capture cats, and help Obasan look after the children, can you make great achievements? People are destined to shoulder the responsibilities of the ninja world and peace.
Similarly, if the absolute positioning attribute is used in a deep DOM tree, it is restricted by relative. It is actually the use of Naruto as the person who looks at the child. Although it is very useful when used, it is actually unable to bury the absolute positioning element. There is no limit to give enough freedom. The vast sky is the stage for absolute positioning elements to shine and save mankind.
Generally, on the web page, the widest sky is the body tag. Therefore, in my opinion, it is King to put the absolute positioning element directly under the body tag, to maximize the potential of absolute positioning elements. For example, the drop-down list on the top of the Taobao homepage.
This drop-down is the absolute positioning, but is deeply embedded into the DOM, as shown in the figure below:
The advantage of this method is that it is simple and can be achieved by directly using CSS for non-IE6 browsers. However, the absolute positioning elements hidden by default are restricted by relative in a deep DOM node. There are many disadvantages: first, the DOM complexity is increased, which is not conducive to maintenance; the deeper the DOM element, this results in stronger reflux. The parent label requires relative restrictions, which increases the consumption of CSS code. The loading of hidden element headers delays the page rendering speed. Almost all pull-down operations must be repositioned, its reusability is limited.
If it is me, these hidden absolute positioning elements will be placed inside the body tag and loaded at the bottom to increase the page rendering speed, or even not loaded at all. This method is recommended for the drop-down navigation of mtime. The positioning of absolute elements is the most direct and efficient method, instead of setting the relative limit of the trigger element, but directly setting the position by triggering the offset value of the element in the body environment.
Freely galloping under the body tag, which is the place where absolute positioning elements really should stay. The truly talented elements should be placed on a larger stage, and they are doomed to be buried in a poor corner. I have previously written a universal floating plug-in named "powerFloat", hoping that by reducing the learning cost of use, we can free everyone from the absolute positioning element to the body tag.
As a result, we don't have to worry about any level of disorder, and we won't see the messy HTML code. For page reconstruction, we should have had a cup of coffee every day and had a crush on the beautiful girl's front-end. But now we have worked so hard, so we should not.
The absolute element is like a bird with wings. Do you want to limit it to a cage or fly it to the sky to fly freely? I think everything goes without saying anything.

 

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.