Items below an item with a relative position and a negative top value remain where they are

I have 3 elements one on top of the other. If I give a second (pink) relative position and a negative top value, it will exceed the first. But the third does not "follow", staying 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 do I make the third and any other elements below it "follow" the pink element?

+3


source to share


8 answers


I'm not really sure what you want to achieve, but I hope everything is correct. put 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

+4


source


You cannot achieve what you want with a CSS rule top

. A negative value top

does not affect the item below. You should use instead margin-top

.

So try:



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

      

DEMO

+7


source


You must use

margin-top: -50px;

      

+2


source


just changing the vertex to the top edge will do the trick

+2


source


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

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

      

Although I don't recommend using negative margins. Use them only as a last resort.

+2


source


Check this link :

      

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

+1


source


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%;
}

      

+1


source


The custom debugger doesn't set the div high. Padding is used for different purposes.

div {
    height:50px;

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

      

0


source







All Articles