drake035
drake035

Reputation: 2897

Elements below an element with relative position and negative top value remain where they are

I have 3 elements one on top of another. If I give the second (pink) one a relative position and negative top value it goes above the first one. But the third one doesn't "follow", remaining exactly where it is:

HTML:

<div id='div1'>text</div>
<div id='div2'>text</div>
<div id='div3'>text</div>

CSS:

div {
    padding: 50px;
}
#div1 {
    background: yellow;
}
#div2 {
    background: pink;
    position: relative;
    top: -50px;
}
#div3 {
    background: gray;
}

Fiddle

How to make the third one and any other elements below it "follow" the pink element?

Upvotes: 3

Views: 1176

Answers (8)

Gandhi
Gandhi

Reputation: 11

You can also give css like this

#div1 {
  background: yellow;
  width:100%;
}
#div2 {
  background: pink;
  position: relative;
  **clear:both;**
  width:100%; 
}
#div3 {
  background: gray;
  width:100%;
}

Upvotes: 1

sasi
sasi

Reputation: 209

Check this link :

http://jsfiddle.net/silpa/dyg86qbq/16/
the above link with position relative and margin-top. Here is the link with position absolute for first div and margin-top for second div. http://jsfiddle.net/silpa/dyg86qbq/22/

Upvotes: 1

Ali
Ali

Reputation: 1336

I am not really sure what you want to achieve, but I hope I get this right. give the following CSS in your third <div>.Just check :)

   position: relative;
   top: -50px;

or,

   margin-top: -50px;

another way,

div {
    padding: 50px;
}
#div1 {
    background: yellow;
    width:100%;
}
#div2 {
    background: pink;
    position: relative;
    top: -50px;
    width:100%;
    float:left;
}
#div3 {
    background: gray;
    width:100%;
}

JSFiddle

Upvotes: 3

Rui Carneiro
Rui Carneiro

Reputation: 5671

They don't follow because you are using absolute positions. If you want to implement the behaviour you describe you need to use blocks.

#div2, #div3 {
    margin-top: -50px;
}

Although I don't recommend you to use negative margins. Only use them as the last resource.

Upvotes: 2

Kayani
Kayani

Reputation: 972

just changing top to margin-top will do the trick

Upvotes: 2

Gus de Boer
Gus de Boer

Reputation: 401

You should use

margin-top: -50px;

Upvotes: 2

laaposto
laaposto

Reputation: 12213

You can't achive what you want with top CSS rule. Negative value at top is not affecting the below element. You have to use margin-top instead.

So try:

#div2 {
    background: pink;
    position: relative;
    margin-top: -70px; /*Here change the top to margin-top*/
}

DEMO

Upvotes: 10

Townsheriff
Townsheriff

Reputation: 709

Dont user padding to set high for divs. Padding is used for different purposes.

div {
    height:50px;

}
#div1 {
    background: yellow;
}
#div2 {
    background: pink;
}
#div3 {
    background: gray;
}

Upvotes: 0

Related Questions