Skip to content Skip to sidebar Skip to footer

Vertical Centering Of Div Without Javascript When Div's Height Isn't Fixed

I would like to vertical center a div without JavaScript when its height isn't fixed. I found here one idea. I wonder if there are other solutions to this problem.

Solution 1:

This works:

Here's link: http://jsbin.com/uvodop/2/edit

See how it's vertically aligned within the box. Height as well isn't fixed.

Hope it answers your question.

<html><head><title>HTML Div vertical align using CSS</title><styletype="text/css">.outerDiv {
            border: solid 1px#000000;
            width: 300px;
            padding: 5px2px5px2px;
        }

        .innerDiv {
            width: 95%;
            margin: 0px auto;
            padding: 40px0px40px5px;
            border: solid 1px#000000;
        }
    </style></head><body><divclass="outerDiv"><divclass="innerDiv">
            This text is placed inside the next HTML div tag.<br />
            CSS style is used to vertical align the nested div and text.
        </div></div></body></html>

Solution 2:

Though this is an old thread, I think this answer might help someone. If the version of IE is flexible to at least IE > 8, then you can use display:table-cell and use the default vertical-align feature.

In the code below, the div.hover which is the div that is going to be vertically aligned middle is not assigned any height however the parent(s) are assigned 100% height to fill the screen.

Check this out

.outer {
  position: fixed;
  top: 0px;
  left: 0px;
  width: 100%;
  height: 100%;
  background-color: #aaa;
  display: table;
}
.inner {
  display: table-row;
  border: 1px solid #0f0;
  height: 100%;
}
.center {
  display: table-cell;
  border: 1px solid #00f;
  vertical-align: middle;
  height: 100%;
}
.hover {
  width:100px;
  border: 1px solid #f00;
  margin-left: auto;
  margin-right: auto;
}
<divclass="outer"><divclass="inner"><divclass="center"><divclass="hover">
        I am a random text to give the div some height
      </div></div></div></div>

Post a Comment for "Vertical Centering Of Div Without Javascript When Div's Height Isn't Fixed"