0

Structure of HTML is the following:

<div id="c1">
  <div id="c2">
    <div id="d1"></div>
    <div id="d2"></div>
  </div>
</div>

I want #c2 to be aligned vertically inside #c1 in such a way that #d2 verticaly centered inside #c1. Here is clarifying picture: enter image description here

It is OK if it will only works in latest Chrome. Thanks.

UPD: Heights of #d1 and #d2 are not fixed. Distance between #d1 and #d2 is fixed.

UPD2: You can forget about #c2. I want #d1 and #d2 to be placed one after another and #d2 to be centered in #c1.

dzhioev
  • 96
  • 1
  • 6
  • 18

3 Answers3

0

HTML :

<div id="c1" style="height:200px;width:250px;">
    <div id="c2" style="height:150px;width:210px;">
        <div id="d1" style="height:50px;width:100px;"></div>
        <div id="d2" style="height:50px;width:100px;"></div>
    </div>
</div>

CSS:

div{
    border:1px solid #ccc;
    padding:5px;
    margin:auto;
}

Check the JSFiddle.

Vucko
  • 20,555
  • 10
  • 56
  • 107
Manish Jangir
  • 505
  • 3
  • 9
0

Use display:table-cell and vertical-align:midddle on parent div

#c1{
    display:table-cell;
    border:red solid 1px;
    width:600px;
    height:300px;
     vertical-align:middle;
    text-align:center
}
#c2{
    border:green solid 1px;
    width:300px;
    margin:0 auto

}

DEMO

Sowmya
  • 26,684
  • 21
  • 96
  • 136
  • Your solution is wrong. http://jsfiddle.net/7tvxM/2/ -- as you can see #d2 not centered. – dzhioev May 28 '13 at 09:21
  • @dzhioev R u new to html/css?? Updated demo here http://jsfiddle.net/7tvxM/3/. I thought you can do that by taking reference of parent div. – Sowmya May 28 '13 at 09:23
  • And I hope you don't need vertical middle alignment to #c2, if not remove display:table-cell and vertical-align:midddle. http://jsfiddle.net/7tvxM/4/ – Sowmya May 28 '13 at 09:26
0

So finally I've found solution by myself. It only works for Chrome because of "-webkit-*" properties, but I think it can be easily adopted for any modern browser. The main idea is to use transform, because transform can refer (by using percentage) to sizes of element itself, not to its parent's sizes. CSS looks like:

div {
    border: 1px solid;
}

#c1 {
    height: 400px;
    width: 400px;
    display: -webkit-flex;
    -webkit-flex-flow: column;
    -webkit-justify-content: center;
    -webkit-align-items: center;
}

#c2 {
    width: 350px;
    position: relative;
}

#d1 {
    width: 200px;
    position: absolute;
    left: 50%;
    top: -20px; /* distance between #d1 and #d2 */
    -webkit-transform: translate(-50%, -100%);
}

#d2 {
    width: 300px;
    margin-left: auto;
    margin-right: auto;
}

JSFIDDLE

dzhioev
  • 96
  • 1
  • 6
  • 18