kunal
kunal

Reputation: 123

HTML, CSS positioning of divs

I want to know how to position multiple div's on each other, without position absolute in HTML.

I tried with position: absolute but due to this, I have to specify container div height explicitly, which I don't want to do.

Upvotes: 0

Views: 1122

Answers (2)

Carele
Carele

Reputation: 784

How do you want to place them exactly ?

If they are div, they should be on top of each other with position: static by defaults. If you don't want to use position: absolute, you could use negative margins. This is not a recommended solution, but the hack definitely works.

.d1 {
  background-color: red;
  height: 200px;
  width: 150px;
 }

.d2 {
  background-color: blue;
  height: 150px;
  width: 100px;
  margin-top: -100px;
 }
<div class="d1"></div>
<div class="d2"></div>

Note that you can use % margins if needed but the % margin properties will always be a percentage of the parent block WIDTH. So be careful with that.

NB : Tanks to @Oriol for correcting mistakes I made. I edited my answer thanks to his advice.

Upvotes: 2

P.Pal
P.Pal

Reputation: 73

Not sure what you're trying to achieve but I can imagine only one scenario, where something like that would be usefull. Namely switching between several divs. If that's the case use display:none on all but the current div.

In anyway child div is by default "overlapping" with parent div, so I assume what you mean is that you want siblings to be "on each other"... however that sounds.

The only way to do this is (except for negative margin hacks) absolute and relative positioning.

Here's how:

#foo{
  background-color:red;
  height: 50px;
  width: 50px;
  position: relative;
}
#bar{
  background-color:blue;
  height: 50px;
  width: 50px;
  position: absolute;
}
#foobar{
  background-color: green;
  height: 50px;
  width: 50px;
  position: absolute;
}
#raboof{
  background-color: yellow;
  height: 50px;
  width: 50px;
}

<div id="foo">
  <div id="bar"></div>
  <div id="foobar"></div>
  <div id="raboof"></div>
</div>

Jsfiddle: https://jsfiddle.net/t81hvsa1/

Keep in mind that: 1. You may but don't need to make last child absolutely positioned. 2. The last absolutely positioned child will always be on top.

Edit: I've just noticed, this question's discussion has all the answers you could possibly want; more elaborate and better formatted at that.

Upvotes: 0

Related Questions