Difference between style = “position:absolute” and

2019-01-02 17:38发布

Can any one tell me the Difference between style = "position:absolute" and style = "position:relative" and how they differ in case I add it to div/span/input elements?

I am using absolute right now, but I want to explore relative as well. How will this change the positioning?

9条回答
闭嘴吧你
2楼-- · 2019-01-02 18:09

OK, very obvious answer here... basically relative position is relative to previous element or window, while absolute don't care about the other elements unless it's a parent if you using top and left...

Look at the example I create for you to show the differences...

enter image description here

Also you can see it in action, using the css I create for you, you can see how absolute and relative positions behave:

.parent {
  display: inline-block;
  width: 180px;
  height: 160px;
  border: 1px solid black;
}

.black {
  position: relative;
  width: 100px;
  height: 30px;
  margin: 5px;
  border: 1px solid black;
}

.red {
  width: 100px;
  height: 30px;
  margin: 5px;
  top: 16px;
  background: red;
  border: 1px solid red;
}

.red-1 {
  position: relative;
}

.red-2 {
  position: absolute;
}
<div class="parent">
  <div class="black">
  </div>
  <div class="red red-1">
  </div>
</div>

<div class="parent">
  <div class="black">
  </div>
  <div class="red red-2">
  </div>
</div>

查看更多
千与千寻千般痛.
3楼-- · 2019-01-02 18:11

With CSS positioning, you can place an element exactly where you want it on your page.

When you are going to use CSS positioning, the first thing you need to do is use the CSS property position to tell the browser if you're going to use absolute or relative positioning.

Both Postion are having different features.In Css Once you set Position then you can able to use top,right,bottom,left attributes.

Absolute Position

An absolute position element is positioned relative to the first parent element that has a position other than static.

Relative Position

A relative positioned element is positioned relative to its normal position.

To position an element relatively, the property position is set as relative. The difference between absolute and relative positioning is how the position is being calculated.

More :Postion Relative vs Absolute

查看更多
春风洒进眼中
4楼-- · 2019-01-02 18:14

Absolute positioning is based on co-ordiantes of the display:

position:absolute;
top:0px;
left:0px;

^ places the element top left of the window.


Relative position is relative to where the element is placed:

position:relative;
top:1px;
left:1px;

^ places the element 1px down and 1px from the left of where it originally sat :)

查看更多
登录 后发表回答