Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85643

What is the difference between position relative and absolute (triangle)?

I'm little surprised while I was creating a triangle using :after pseudo class. Why position absolute works fine but not position relative. Look at the below code

.test {
  position: relative;
}

.abs {
  position: absolute;
  left: 180px;
  top: 0px;
  background: red;
  width: 300px;
  padding: 10px;
}

.abs:after {
  position: absolute; /* by changing this value to relative */
  left: -20px;
  top: 0px;
  border-top: 20px solid transparent;
  border-bottom: 20px solid transparent;
  border-right: 20px solid blue;
  width: 0;
  height: 0;
  content: " ";
}
<div class="test">
  <input type="text" />
  <div class="abs">enter your name</div>
</div>

demo with absolute | demo with relative

Can anyone picturize the reason for this?

Upvotes: 2

Views: 1061

Answers (2)

bfavaretto
bfavaretto

Reputation: 71939

The cause is that the technique you're using to create the triangle doesn't work with inline elements, and :after pseudo-elements are inline by default. See a test with a simple span: http://jsfiddle.net/YBLpL/.

When you use position: absolute, the inline element is considered a block, according to section 9.7 of the CSS 2 specification.


Note: although your question seems to be about the meaning of absolute vs. relative, it's actually about the broken shape of the triangle, as you clarified in the comments to the answers (including one deleted answer). You should edit the question to clarify your point.

Upvotes: 2

gp.
gp.

Reputation: 8225

:after psudo class adds the content after the content of .abs div but is a child of the .abs div. That would explain the relative and absolute behavior of the inserted content.

When you make the inserted content position relative then it's supposed to be after the original content i.e. "enter your name" as it's part of the visual flow. whereas if you make this absolute, it's removed from the visual flow and so it positioned in the beginning or as per left, right values with respect to the parent .abs div.

Upvotes: 0

Related Questions