CSS 位置相对与绝对?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10426497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 03:45:37  来源:igfitidea点击:

Position Relative vs Absolute?

css

提问by Arvind S Salunke

What is the difference between position: relativeand position: absolutein CSS? And when should you use which?

CSS 中position: relative和之间有什么区别position: absolute?什么时候应该使用哪个?

回答by Michael Zaporozhets

Absolute CSS Positioning

绝对 CSS 定位

position: absolute;

position: absolute;

Absolute positioning is the easiest to understand. You start with the CSS positionproperty:

绝对定位是最容易理解的。你从 CSSposition属性开始:

position: absolute;

This tells the browser that whatever is going to be positioned should be removed from the normal flow of the document and will be placed in an exact location on the page. It won't affect how the elements before it or after it in the HTML are positioned on the Web page however it willbe subject to it's parents' positioning unless you override it.

这告诉浏览器将要定位的任何内容都应该从文档的正常流中删除,并将放置在页面上的确切位置。它不会影响 HTML 中它之前或之后的元素在网页上的定位方式,但是除非您覆盖它,否则它将受制于它的父级定位。

If you want to position an element 10 pixels from the top of the document window, you would use the topoffset to positionit there with absolutepositioning:

如果您想将一个元素定位在距文档窗口顶部 10 像素的位置,您可以使用定位topposition它的偏移量absolute

position: absolute;
top: 10px;

This element will then always display 10pxfrom the top of the page regardless of what content passes through, under or over the element (visually).

该元素将始终10px从页面顶部显示,无论什么内容通过、下方或上方元素(视觉上)。

The four positioning properties are:

四个定位属性是:

  1. top
  2. right
  3. bottom
  4. left
  1. top
  2. right
  3. bottom
  4. left

To use them, you need to think of them as offset properties. In other words, an element positioned right: 2pxis not moved right 2px. It's right side is offset from the right side of the window (or its position overriding parent) by 2px. The same is true for the other three.

要使用它们,您需要将它们视为偏移属性。换句话说,定位的元素right: 2px不会向右移动2px。它的右侧从窗口的右侧(或其覆盖父级的位置)偏移2px. 其他三个也是同样的道理。

Relative Positioning

相对定位

position: relative;

position: relative;

Relative positioning uses the same four positioning properties as absolutepositioning. But instead of basing the position of the element upon the browser view port, it starts from where the element would be if it were still in the normal flow.

相对定位使用与定位相同的四个定位属性absolute。但不是将元素的位置基于浏览器视图端口,而是从元素仍在正常流中的位置开始

For example, if you have three paragraphs on your Web page, and the third has a position: relativestyle placed on it, its position will be offset based on its current location-- not from the original sides of the view port.

例如,如果您的网页上有三个段落,而第三个段落上position: relative放置了一个样式,则其位置将根据其当前位置进行偏移,而不是从视口的原始侧面偏移。

Paragraph 1.

第 1 段。

Paragraph 2.

第 2 段。

第 3 段。

在上面的例子中,第三个段落将从3em3em容器元素的左侧定位,但仍会在前两个段落的下方。它将保留在文档的正常流程中,只是稍微偏移。如果将其更改为position: absolute;position: absolute;,则其后的任何内容都会显示在其顶部,因为它将不再处于文档的正常流程中。

Notes:

笔记:

  • the default widthof an element that is absolutely positioned is the width of the content within it, unlike an element that is relatively positioned where it's default widthis 100%of the space it can fill.

  • You can have elements that overlap with absolutely positioned elements, whereas you cannot do this with relatively positioned elements (natively i.e without the use of negative margins/positioning)

  • 默认width的是绝对定位的元素的是在其中的内容的宽度,不同于被相对定位在那里它的默认的元素width100%该空间也可以填充的。

  • 你可以让元素与绝对定位的元素重叠,而你不能用相对定位的元素来做到这一点(原生即不使用负边距/定位)



lots pulled from: this resource

很多来自: 这个资源

回答by Jukka K. Korpela

Both “relative” and “absolute” positioning are really relative, just with different framework. “Absolute” positioning is relative to the position of another, enclosing element. “Relative” positioning is relative to the position that the element itself would have without positioning.

“相对”和“绝对”定位都是相对的,只是框架不同。“绝对”定位是相对于另一个封闭元素的位置。“相对”定位是相对于元素本身没有定位时的位置。

It depends on your needs and goals which one you use. “Relative” position is suitable when you wish to displace an element from the position it would otherwise have in the flow of elements, e.g. to make some characters appear in a superscript position. “Absolute” positioning is suitable for placing an element in some system of coordinates set by another element, e.g. to “overprint” an image with some text.

这取决于您使用的需求和目标。“相对”位置适用于当您希望将元素从元素流中原本应具有的位置移开时,例如使某些字符出现在上标位置。“绝对”定位适用于将一个元素放置在由另一个元素设置的某个坐标系统中,例如用某些文本“套印”图像。

As a special, use “relative” positioning with no displacement (just setting position: relative) to make an element a frame of reference, so that you can use “absolute” positioning for elements that are inside it (in markup).

作为一种特殊情况,使用没有位移的“相对”定位(只是设置position: relative)使元素成为参考框架,以便您可以对其中的元素(在标记中)使用“绝对”定位。

回答by Troy Grosfield

Another thing to note is that if you want a absolute element to be confined to a parent element then you need to set the parent element's position to relative. That will keep the child element contained within the parent element and it won't be "relative" to the entire window.

另外要注意的是,如果您希望将绝对元素限制在父元素中,那么您需要将父元素的位置设置为相对。这将使子元素包含在父元素中,并且不会“相对”于整个窗口。

I wrote a blog postthat gives a simple example that creates the following affect:

我写了一篇博客文章,给出了一个简单的例子,可以产生以下影响:

enter image description here

在此处输入图片说明

That has a green div that is absolutely positioned to the bottom of the parent yellow div.

它有一个绝对位于父黄色 div 底部的绿色 div。

1http://blog.troygrosfield.com/2013/02/11/working-with-css-positions-creating-a-simple-progress-bar/

1 http://blog.troygrosfield.com/2013/02/11/working-with-css-positions-creating-a-simple-progress-bar/

回答by coder

Position Relative:

职位相对:

If you specify position:relative, then you can use top or bottom, and left or right to move the element relative to where it would normally occur in the document.

如果您指定 position:relative,那么您可以使用 top 或 bottom 以及 left 或 right 相对于它在文档中通常出现的位置移动元素。

Position Absolute:

绝对位置:

When you specify position:absolute, the element is removed from the document and placed exactly where you tell it to go.

当您指定 position:absolute 时,该元素将从文档中移除并准确放置在您指定的位置。

Here is a good tutorial http://www.barelyfitz.com/screencast/html-training/css/positioning/with the sample usage of both position with respective to absolute and relative positioning.

这是一个很好的教程http://www.barelyfitz.com/screencast/html-training/css/positioning/与绝对和相对定位的两个位置的示例用法。

回答by Arif

Relative :Relative to it's current position, but can be moved. Or A RELATIVE positioned element is positioned relative to ITSELF.

相对:相对于它的当前位置,但可以移动。或者 A RELATIVE 定位元素相对于 ITSELF 定位。

Absolute :An ABSOLUTE positioned element is positioned relative to IT'S CLOSEST POSITIONED PARENT. if one is present, then it works like fixed.....relative to the window.

Absolute :一个绝对定位的元素是相对于它的最近定位的父元素定位的。如果存在,那么它就像固定的一样......相对于窗口。

<div style="position:relative"> <!--2nd parent div-->
    <div>   <!--1st parent div-->
        <div style="position:absolute;left:10px;....."> <!--Middle div-->
          Md. Arif
       </div>
    </div>
</div>

Here, 2nd parent divposition is relative so the middle divwill changes it's position with respect to 2nd parent div. If 1st parent divposition would relative then the Middle divwould changes it's position with respect to 1st parent div. Details

在这里,第二个父div位置是相对的,所以中间div会改变它相对于第二个父的位置div。如果第一个父div位置是相对的,那么 Middlediv会改变它相对于 1st parent 的位置div细节

回答by sunto

Putting an answer , as my reputation aint enough to comment. But dont look at this as an answer, just a additional info, as myself, had some problems with both footer, and positioning.

给出答案,因为我的声誉不足以发表评论。但是不要将其视为答案,只是附加信息,因为我自己在页脚和定位方面都有一些问题。

When setting up the page, so that my footer always stays at the bottom, with position absolute, and main container/wrapper with relative position.

设置页面时,使我的页脚始终位于底部,位置绝对,主容器/包装器具有相对位置。

I then found some issues with my text content, and a menu inside the same content(white part of page between header and footer), when setting these to absolute, footer no longer stays down.

然后我发现我的文本内容和相同内容中的菜单(页眉和页脚之间的页面白色部分)存在一些问题,当将这些设置为绝对时,页脚不再保持向下。

Postitioning is, as you say a complex theme.

正如您所说,定位是一个复杂的主题。

My solution, to the content I wanted in 'absolute' positon in my webpage, and not be pushed to the side, when in example opening a drop down menu, was to actually give it postition relative, and putting it 35em below my drop down menu. (35em is the heigth of my dropdown menu, when fully extended)

我的解决方案,对于我想要在我的网页中的“绝对”位置的内容,而不是被推到一边,在示例中打开下拉菜单时,实际上是给它相对位置,并将其放在我的下拉菜单下方 35em菜单。(35em 是我的下拉菜单的高度,当完全展开时)

Then, Top:-35em, for the content that before was pushed to the side. And then adding margin-bottom:-35em. This way, the content is "below" my drop down menu, but visually it is side by side with my drop down menu! And the white space below down to the footer, is with only 10em margin, as it was before starting to play around with this. So my solution to this was like this :

然后,Top:-35em,用于之前被推到一边的内容。然后添加 margin-bottom:-35em。这样,内容在我的下拉菜单“下方”,但在视觉上它与我的下拉菜单并排!下方到页脚的空白只有 10em 边距,就像在开始玩这个之前一样。所以我对此的解决方案是这样的:

 html, body {
    margin:0;
    padding:0;
    height:100%;

}
h1 {
    margin:0;
}
    #webpage {
    position:relative;
    min-height:100%;
    margin:0;
    overflow:auto;
}
     #header {
    height:5em;
    width:100%;
    padding:0;
    margin:0;
}
     #text {
    position:relative;
   margin-bottom:-32em;
    padding-top:2em;
    padding-right:2em;
    padding-bottom:10em;
    background-repeat:no-repeat;
    width:70%;
    padding-left:auto;
    margin-left:auto;
    margin-right:auto;
    right:10em;
    float:right;
    top:-32em;
      }
#dropdown {

position:absolute;
    left:0;
    width:20%;
    clear:both;
    display:block;
    position:relative;
    top:1em;
    height:35em;

}
    #footer {
    position:absolute;
    width:100%;
    right:0;
    bottom:0;
    height:5em;
    margin:0;
     margin-top:5em;
}

I see your question is answered good, but after alot of troubleing I found this to be a very good solution, and a way to understand better how positioning works.. When I place my text content, below my drop down menu, it doesn't push my text to the side. If I changed the text to position absolute, the footer did not stay in place. As I can believe this is an issue for more people then me, I add this here. What in fact happends, is I put the text, 35ems, below my drop down.

我看到您的问题得到了很好的回答,但是经过很多麻烦之后,我发现这是一个非常好的解决方案,并且是一种更好地了解定位如何工作的方法。当我将文本内容放在下拉菜单下方时,它不会把我的文字推到一边。如果我将文本更改为绝对位置,则页脚不会保持原位。因为我可以相信这是一个比我更多的人的问题,我在这里添加这个。事实上,我将文本 35ems 放在下拉菜单的下方。

Then, I visually put it right next to eachother, with relative position, and top:-35em;, and evening out the huge space below, with margin:-35em;

然后,我在视觉上将它放在彼此相邻的位置,相对位置,顶部:-35em;,并将下方的巨大空间均匀化,边距:-35em;

negative values are underestimated at times, very good functionality, when one understands these positions better!

负值有时会被低估,非常好的功能,当人们更好地理解这些位置时!

Natually, fixed position, also seemed logic for my footer, but I do really want the footer to go below the viewport, if the text, or content, is longer than the viewport. And to stay at the bottom, if there is little content on the page.

自然地,固定位置对于我的页脚来说也是合乎逻辑的,但我确实希望页脚位于视口下方,如果文本或内容比视口长。并留在底部,如果页面上的内容很少。

This setupp fixed that very nicely, and remember to use 'em', not 'px' for a more fluid/dynamic page layout! :)

这个 setupp 很好地解决了这个问题,记住使用 'em',而不是 'px' 以获得更流畅/动态的页面布局!:)

(there may be better solutions, but this works for me cross platforms, as well as devices).

(可能有更好的解决方案,但这对我来说适用于跨平台和设备)。

回答by Haris Ghauri

Relative vs Absolute:

相对与绝对:

  • Difference:relative to itself, relative to the nearest positioned ancestor.
  • Difference:Other elements arounds it honour its old existence, Other elements around it DO NOT honour its old existence.
  • Similarity:Other elements arounds it DO NOT honour its new existence, Other elements around it DO NOT honour its new existence.
  • 差异:相对于自身,相对于最近定位的祖先。
  • 区别:它周围的其他元素尊重它的旧存在,它周围的其他元素不尊重它的旧存在。
  • 相似性:它周围的其他元素不尊重它的新存在,它周围的其他元素不尊重它的新存在。

回答by sumit

Let's discuss a scenario to explain the difference between absolute vs relative.

让我们讨论一个场景来解释绝对与相对之间的区别。

Inside the body element say you have an header element whose height is 95% of viewheight i.e 95vh. Within this container you placed an image and reduced it's opacity to say 0.5. And now you want to place a logo image near the top left corner. I hope you understood the scenario. So you will have a lighter image in the header section with a logo on the top of it at the specified position.

在 body 元素内部,假设您有一个高度为 viewheight 的 95% 的 header 元素,即 95vh。在这个容器中,您放置了一个图像并将其不透明度降低到 0.5。现在您想在左上角附近放置一个徽标图像。我希望你理解这个场景。因此,您将在标题部分有一个更亮的图像,在其顶部的指定位置有一个徽标。

But before starting this, i have set margin and padding to 0 like this

但在开始之前,我已经像这样将边距和填充设置为 0

*{
   margin:0px;
   padding:0px;
   box-sizing: border-box; 
}

This ensures no default margins and padding is applied to elements.

这确保没有默认边距和填充应用于元素。

So you can achieve your requirement in two ways.

因此,您可以通过两种方式实现您的要求。

First Way

第一种方式

  • you give a class to the image say logo.
  • in css you write

    .logo{ float:left; margin-top:40px; margin-left:40px; }

  • this placed the logo to the 40px from the top and left of the enclosing parent which is the header. The image will appear as if it placed as desired.
  • 你给图像一个类说标志。
  • 在 css 中你写

    .logo{ float:left; margin-top:40px; margin-left:40px; }

  • 这将徽标放置在距离作为标题的封闭父级的顶部和左侧 40 像素处。图像看起来就像是按需要放置一样。

But my friend this is a bad design as to place an image you unnecessarily consumed so much of space around by giving it some margin when it was not required. All you needed is to place the image to that location. You managed it by cushioning it with margins around. The margin took space and pushed it's content deeper giving an impression that it is positioned exactly where you wanted. Hope you understood the issue by working it around like this. You are taking more space than required to place just an image at the desired location.

但是我的朋友,这是一个糟糕的设计,因为在不需要时给它一些余量,从而将不必要地消耗了大量空间的图像放置在图像上。您所需要做的就是将图像放置到该位置。你通过用周围的边距缓冲它来管理它。边距占据了空间并将其内容推得更深,给人的印象是它正好位于您想要的位置。希望你通过像这样解决这个问题来理解这个问题。您占用的空间超出了将图像放置在所需位置所需的空间。

Now let's try a different approach.

现在让我们尝试不同的方法。

Second Way

第二种方式

  • the image with logo class is inside the header element with say header class. So the parent class is header and the child class is logo as before.
  • you set the position property of the header class to relative like this

    .header{ position: relative; }

  • then you added the following properties to the logo class

    .logo{ position:absolute; top:40px; left:40px }

  • 带有徽标类的图像位于带有say header 类的header 元素内。所以父类是header,子类和以前一样是logo。
  • 你像这样将头类的位置属性设置为相对

    .header{ position: relative; }

  • 然后您将以下属性添加到徽标类

    .logo{ position:absolute; top:40px; left:40px }

There you go. You placed the image at exactly the same place. There won't be any apparent difference in the positioning from the naked eye between the first approach and second approach. But if you inspect the image element , you will find that it has not taken any extra space. It's occupying exactly the same area as much as it's own width and height.

你去吧。您将图像放置在完全相同的位置。第一种方法和第二种方法之间的肉眼定位不会有任何明显差异。但是如果你检查图像元素,你会发现它没有占用任何额外的空间。它占据的面积与它自己的宽度和高度完全相同。

So how is this possible? I said to the image logo class that you will be placed relativeto the header class as you are the child of this class and that i specifically mentioned it's position as relative. So that any child of it's will be placed relative to it's top left corner. And that Your position need to be fixed inside this parent element. so you are given absolute. And That you need to move a little from top and left to the position i want you to be. Hence you are given top and left property with 40px as value. In this way you will be placed relative to your parent only. So if tomorrow i move your parent up or down or just anywhere, you will always be 40px to the top and left of your parent header's top left corner. So your position is fixed inside your parent no matter whether your parent's position is fixed or not in future(as it is not absolute like you).

那么这怎么可能呢?我对图像徽标类说,您将对于标题类放置,因为您是该类的子类,并且我特别提到它的位置为relative。这样它的任何孩子都将相对于它的左上角放置。你的位置需要固定在这个父元素内。所以你被赋予了绝对的. 而且你需要从顶部向左移动一点到我希望你成为的位置。因此,您将获得 top 和 left 属性,其值为 40px。通过这种方式,您将仅相对于您的父母。因此,如果明天我将您的父级向上或向下移动或随意移动,您将始终位于父级标题左上角的左上角 40 像素处。所以无论你父母的位置将来是否固定(因为它不像你那样绝对),你的位置在你的父母内部是固定的。

So use relative and absolute for parent and child respectively. Secondly use it when you want to only place the child element at some location inside it's parent element. Do not use fillers like margins to push it forcibly. Give parent relative value and child which you want to move, the absolute value. Specify top, left bottom or right property to child class to place it inside parent anywhere you want.

因此,分别为父和子使用相对和绝对。其次,当您只想将子元素放置在其父元素内的某个位置时,请使用它。请勿使用边距之类的填充物强行推动。给父相对值和要移动的子,绝对值。为子类指定 top、left bottom 或 right 属性以将其放置在父类中您想要的任何位置。

Thanks.

谢谢。

回答by Marquinho Peli

Marco Pellicciotta: The position of the element inside another element can be relative or absolute, about the element it's inside.

Marco Pellicciotta:元素在另一个元素内的位置可以是相对的或绝对的,关于它所在的元素。

If you need to position the element in the browser window point of view it's best to use position:fixed

如果您需要在浏览器窗口的角度定位元素,最好使用 position:fixed