0

I have 2 divs, a square and a bar. Both are centered using auto margin. But I want to place bar over square. How can I do this?

html

<div class="square">square</div>
<div class="bar">square</div>

css

.square,.bar{
    margin-left:auto;
    margin-right:auto
}
.square{
    background-color:blue;
    width: 100px;
    height: 100px;
}
.bar{
    background-color:green;
    width: 400px;
    height: 40px;
}

Here is the fiddle.

halfer
  • 19,824
  • 17
  • 99
  • 186
Alfred
  • 21,058
  • 61
  • 167
  • 249

2 Answers2

0

You could do it like this: http://jsfiddle.net/mz6rk/

I made position:relative and placed the bar at -square_height/2 - bar_height/2

This does assume you know the height of both the square and bar though, I don't know if that's always the case..

UPDATE: Actually, only the bar needs to have position:relative (I put it on both in the fiddle).

myfunkyside
  • 3,890
  • 1
  • 17
  • 32
0

http://jsfiddle.net/atomicrevolution/P9yWK/5/

Is this what you mean?

.square,.bar{
    margin-left:auto;
    margin-right:auto;
}
.square{
    background-color:blue;
    width: 100px;
    height: 100px;
    position: relative;
}
.bar{
    background-color:green;
    width: 400px;
    height: 40px;
    position: relative;
    margin-top: -70px;
}