George Irimiciuc
George Irimiciuc

Reputation: 4633

Content after relative placed div

If I display a div relatively and give it a top margin, do I have to give all the following content the same top margin as well? Because the content that follows will be after the element's regular position.

http://jsfiddle.net/u9cgu6er/

As you can see here, the blue div is over the red one, which just follows blue's original position.

Is there a way to make red 20px lower without making it relative, as well? In other words, not do that with all the following content.

#a {
  width:100%;
  background-color:yellow;
  height:50px;
}
#b {
  position:relative;
  top:20px;
  width:50%;
  background-color:blue;
  height:50px;
}
#c {
  width:100%;
  background-color:red;
  height:50px;
}
<div id="a"></div>
<div id="b"></div>
<div id="c"></div>

Upvotes: 2

Views: 60

Answers (4)

Pipo
Pipo

Reputation: 988

Add margin-top: 20px; to your #c. @HashemQolami is right, it will be easier to maintain your css by using margin-top on #b instead of position relative if you can.

Upvotes: 3

Alex Char
Alex Char

Reputation: 33218

You can add margin-bottom: 40px; to #b element:

#a {
    width:100%;
    background-color:yellow;
    height:50px;
}
#b {
    position:relative;
    top:20px;
    width:50%;
    background-color:blue;
    height:50px;
    margin-bottom: 40px;
}
#c {
    width:100%;
    background-color:red;
    height:50px;
}
<div id="a"></div>
<div id="b"></div>
<div id="c"></div>

or margin-top: 40px; to #c element:

#a {
    width:100%;
    background-color:yellow;
    height:50px;
}
#b {
    position:relative;
    top:20px;
    width:50%;
    background-color:blue;
    height:50px;
    
}
#c {
    width:100%;
    background-color:red;
    height:50px;
    margin-top: 40px;
}
<div id="a"></div>
<div id="b"></div>
<div id="c"></div>

Either will work.

Upvotes: 2

KM123
KM123

Reputation: 1377

Add margin 40px to the top of #c

Upvotes: 1

Scimonster
Scimonster

Reputation: 33399

The easiest thing would be to just set the margin-top of #b to 20px, and then #c will follow it.

#a {
  width:100%;
  background-color:yellow;
  height:50px;
}
#b {
  margin-top:20px;
  width:50%;
  background-color:blue;
  height:50px;
}
#c {
  width:100%;
  background-color:red;
  height:50px;
}
<div id="a"></div>
<div id="b"></div>
<div id="c"></div>

This way, it doesn't remove #b from the document flow.

Upvotes: 3

Related Questions