Ok this is the div structure.
<div class="DivParent">
<a href="#">
<div class="DivWhichNeedToBeVerticallyAligned"></div>
</a>
</div>
DivParent has fixed width and height values but DivWhichNeedToBeVerticallyAligned does not have fixed height values.
If you make DivParent display:table-cell; you can vertically align DivWhichNeedToBeVerticallyAligned but i don't want to use that feature since it causes some mess.
A href tag link should be same size with the divParent i mean whole divparent has to be clickable. like display:block.
So are there any CSS way of vertically aligning or lightweight jquery solution would also help.
Thank you.
Here jsfiddle : http://jsfiddle.net/XHK2Z/
*
You can use an extra helper to achieve vertical alignment in a block with fixed height.
Look at this: http://jsfiddle.net/kizu/7Fewx/
There you must have a helper near a block you want to align with:
.DivHelper {
display: inline-block;
vertical-align: middle;
height:100%;
}
And add display: inline-block; vertical-align: middle;
to .DivWhichNeedToBeVerticallyAligned
There is no way to do this with CSS without knowing the height of the child div.
With jQuery, you could do something like this.
var parentHeight = $('#parent').height();
var childHeight = $('#child').height();
$('#child').css('margin-top', (parentHeight - childHeight) / 2);
if the parent don't have any other child. this would be a css only "hack"
DivParent{line-height:100px /*the div actual height*/ }
.DivWhichNeedToBeVerticallyAligned{display:inline-block}
another hack is
DivParent{height:100px; position:relative}
.DivWhichNeedToBeVerticallyAligned{height:20px; position:absolute; top:50%; margin-top:-10px;}
This solution works for me fine in modern browsers including IE 10 and above.
<div class="parent">
<div class="child">Content here</div>
</div>
inlucluding this css
.parent {
height: 700px;
display: flex;
justify-content: center;
align-items: center;
}
.child {
width : 525px;
}
I have been using the following solution (with no positioning, no table-cell/table-row and no line height) since over a year, it works with IE 7 and 8 as well.
<style>
.outer {
font-size: 0;
width: 400px;
height: 400px;
background: orange;
text-align: center;
display: inline-block;
}
.outer .emptyDiv {
height: 100%;
background: orange;
visibility: collapse;
}
.outer .inner {
padding: 10px;
background: red;
font: bold 12px Arial;
}
.verticalCenter {
display: inline-block;
*display: inline;
zoom: 1;
vertical-align: middle;
}
</style>
<div class="outer">
<div class="emptyDiv verticalCenter"></div>
<div class="inner verticalCenter">
<p>Line 1</p>
<p>Line 2</p>
</div>
</div>
Here is another option for modern browsers:
.child {
position: absolute;
left: 50%;
top: 50%;
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
-o-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}