search
HomeWeb Front-endHTML TutorialDetailed explanation of relative positioning and absolute positioning of CSS

Detailed explanation of relative positioning and absolute positioning of CSS

Jun 09, 2017 am 11:20 AM
cssrelative positioningabsolute positioning

CSS relative positioning and absolute positioning
Normally, the value of the position attribute of our element defaults to static, which means there is no positioning. The element appears in the normal document flow. At this time, you The offset attributes of left, right, bottom, and top set for this element have no effect and will not take effect. For example, if you set a statement with an offset of 100px from the left margin: left:100px, then this statement will not have any effect. any effect. The z-index attribute will not take effect at this time.
That is to say, if we usually don’t declare a position attribute to an element, then it will default to the situation I mentioned above. However, because of floats, usually we don’t really need to set a position for the element. property!
But in some special cases, we have to use the position attribute, so today we will talk about the relative and absolute values ​​of the position attribute
First of all, let’s talk about relative, relative positioning.
How to understand? If I set relative positioning for an element, then first, like other elements, this element will appear where it should appear in the document flow. Then, we can set its horizontal or vertical offset to make this The element is moved relative to the starting point of its position in the document flow. One thing to note is that when using relative positioning, even if the element is offset, it still occupies the space before it was offset. One thing worth noting here is that offset is not the same as margin.
Let’s take a look at the picture below:
Detailed explanation of relative positioning and absolute positioning of CSS 三联
There are three floating blocks in the picture above. The second block has relative positioning set: relative. Now you can see it There is no other difference in position, it is in the normal document flow like the other two blocks.
Next, I set an offset for the block with position:relative: left:50px; top:30px. Then we take a look at the effect:

At this time we find the second The block is offset from the starting point of its own position, but the position space it originally occupied is still there (the place marked by the dotted box), even if we set the offset larger to make it completely After leaving its original position, its original position in the document flow will still exist and will not be filled by the third block floating over.
At the same time, its offset will not push other blocks away from their original positions in the document flow. If there is overlap, it will overlap on other document flow elements instead of pushing them away. Like in the picture, it has been overlaid on top of the third block.
We can set its z-index property to adjust its stacking order.
Next let’s take a look at absolute positioning: position:absolute
An element that is set to absolute positioning does not occupy space in the document flow. If an element is set to absolute positioning, then it is in the document flow. The position will be deleted, so where does this element go? It floats. In fact, setting relative positioning will also make the element float. But the difference between them is that relative positioning will not delete the space it occupies in the document flow, while absolute positioning will. Delete the position of the element in the document flow and completely extract it from the document flow. We can set their stacking order through z-index.
So how is absolute positioning positioned? First, if its parent element sets a position other than static, such as position:relative, or position:absolute and position:fixed, then it will be positioned relative to its parent element, and the position is passed through left, top, right , bottom attribute stipulates that if its parent element does not have positioning set, then it depends on whether the parent element of its parent element has positioning set. If it still does not, continue to the higher-level ancestor element and so on. In short, its positioning is relative to The first ancestor element with a position other than static positioning (such as position:relative) is set. If all ancestor elements do not have one of the above three positionings, then it will be relative to Document body is positioned (not the window, positioning relative to the window is fixed) [Note the difference between the two, can To understand from the picture attached at the bottom, the red border is the border of the window body, The purple background color is the part of the document body]

Absolutely positioned elements are positioned relative to who, we call this "who" the reference object. Let's take a look at the picture below based on the above explanation:

Let's take a look Let’s first take a look at the effect in the browser without using absolute positioning:



Then we set the absolute positioning for the second block: position:absolute and then set an offset: left:150px;top:40px; At this time, it becomes the following picture Display:


Another point is: when setting the offset, we can set a negative value.
Okay, now that we understand relative positioning and absolute positioning, how should we apply them to actual cases?
First, let’s take a look at the picture below:

In the picture above, there is a small red block on the upper left side of the shopping cart checkout button to show how many items are in the shopping cart. You may not know how to implement this small red block before you learned absolute positioning, but now that you have just learned absolute positioning, this problem is no longer a problem.
Let me do it myself. Let’s get this background image first:

Then we write HTML:


 155
Go to the shopping cart to checkout
, the b element is the rightmost small triangle.
Let’s take a look at the CSS code:

.cart_btn{width:120px;height:30px;background:url(../images/picA.png) no-repeat -17px 7px#f7f7f7;border:1px solid #eee;padding-left:30px;position:relative;_padding-top:5px;_height:25px;}

.cart_btn span{background:url(../images/picA.png) no-repeat -36px - 54px;padding-left:7px;position:absolute; top:-12px;left:20px;}
.cart_btn span i{float:left;height:20px;background:url(../images/picA.png ) no-repeat right-25px;padding-right:5px;font-style:normal;color:#fff;font-size:14px;}
.cart_btn a{color:#aaa;text-decoration:none; font-size:14px;padding-left:15px;line-height:30px;}
.cart_btn b{display:inline-block;border-color:transparent transparent transparent #CCCCCC;border-style:dashed dashed dashed solid ;border-width:5px;height: 0;overflow: hidden;width: 0;}
In the above CSS code, we use the shopping cart icon as the background of .cart_btn. Here we find a problem, that is, on that picture There are three icons, and you have also discovered that the three elements that use icons all use this picture as the background, but they are displayed differently. The background positioning problem we talked about earlier is used here. No. Friends, please check out the previous lecture 11:
Detailed explanation of the css background attribute background - using background images

What does the content in CSS mean? I won’t go into it here. If I want to talk about it, I will go off topic. Yes, these are basic things. If you don’t know how to do anything else except the CSS triangle, then you must not have read the previous article carefully. Besides, if you really don’t understand, you can check the reference manual
Finally, let’s take a look at the effect in the browser:


Absolute positioning is relative to Document body (not the window, fixed relative to the window) [Note the difference between the two, which can be understood through a picture. The red border
box is the border of the window body, and the purple background color is the document body Detailed explanation of relative positioning and absolute positioning of CSS Part of ]

The above is a detailed explanation of relative positioning and absolute positioning of CSS, and more For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!



Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
HTML vs. CSS vs. JavaScript: A Comparative OverviewHTML vs. CSS vs. JavaScript: A Comparative OverviewApr 16, 2025 am 12:04 AM

The roles of HTML, CSS and JavaScript in web development are: HTML is responsible for content structure, CSS is responsible for style, and JavaScript is responsible for dynamic behavior. 1. HTML defines the web page structure and content through tags to ensure semantics. 2. CSS controls the web page style through selectors and attributes to make it beautiful and easy to read. 3. JavaScript controls web page behavior through scripts to achieve dynamic and interactive functions.

HTML: Is It a Programming Language or Something Else?HTML: Is It a Programming Language or Something Else?Apr 15, 2025 am 12:13 AM

HTMLisnotaprogramminglanguage;itisamarkuplanguage.1)HTMLstructuresandformatswebcontentusingtags.2)ItworkswithCSSforstylingandJavaScriptforinteractivity,enhancingwebdevelopment.

HTML: Building the Structure of Web PagesHTML: Building the Structure of Web PagesApr 14, 2025 am 12:14 AM

HTML is the cornerstone of building web page structure. 1. HTML defines the content structure and semantics, and uses, etc. tags. 2. Provide semantic markers, such as, etc., to improve SEO effect. 3. To realize user interaction through tags, pay attention to form verification. 4. Use advanced elements such as, combined with JavaScript to achieve dynamic effects. 5. Common errors include unclosed labels and unquoted attribute values, and verification tools are required. 6. Optimization strategies include reducing HTTP requests, compressing HTML, using semantic tags, etc.

From Text to Websites: The Power of HTMLFrom Text to Websites: The Power of HTMLApr 13, 2025 am 12:07 AM

HTML is a language used to build web pages, defining web page structure and content through tags and attributes. 1) HTML organizes document structure through tags, such as,. 2) The browser parses HTML to build the DOM and renders the web page. 3) New features of HTML5, such as, enhance multimedia functions. 4) Common errors include unclosed labels and unquoted attribute values. 5) Optimization suggestions include using semantic tags and reducing file size.

Understanding HTML, CSS, and JavaScript: A Beginner's GuideUnderstanding HTML, CSS, and JavaScript: A Beginner's GuideApr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

The Role of HTML: Structuring Web ContentThe Role of HTML: Structuring Web ContentApr 11, 2025 am 12:12 AM

The role of HTML is to define the structure and content of a web page through tags and attributes. 1. HTML organizes content through tags such as , making it easy to read and understand. 2. Use semantic tags such as, etc. to enhance accessibility and SEO. 3. Optimizing HTML code can improve web page loading speed and user experience.

HTML and Code: A Closer Look at the TerminologyHTML and Code: A Closer Look at the TerminologyApr 10, 2025 am 09:28 AM

HTMLisaspecifictypeofcodefocusedonstructuringwebcontent,while"code"broadlyincludeslanguageslikeJavaScriptandPythonforfunctionality.1)HTMLdefineswebpagestructureusingtags.2)"Code"encompassesawiderrangeoflanguagesforlogicandinteract

HTML, CSS, and JavaScript: Essential Tools for Web DevelopersHTML, CSS, and JavaScript: Essential Tools for Web DevelopersApr 09, 2025 am 12:12 AM

HTML, CSS and JavaScript are the three pillars of web development. 1. HTML defines the web page structure and uses tags such as, etc. 2. CSS controls the web page style, using selectors and attributes such as color, font-size, etc. 3. JavaScript realizes dynamic effects and interaction, through event monitoring and DOM operations.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft