With CSS 3, are there any way to vertically align an block element? Do you have an example? Thank you.
a couple ways:
1. Absolute positioning-- you need to have a declared height to make this work:
<div>
<div class='center'>Hey</div>
</div>
div {height: 100%; width: 100%; position: relative}
div.center {
width: 100px;
height: 100px;
top: 50%;
margin-top: -50px;
}
*2. Use display: table http://jsfiddle.net/B7CpL/2/ *
<div>
<img src="/img.png" />
<div class="text">text centered with image</div>
</div>
div {
display: table;
vertical-align: middle
}
div img,
div.text {
display: table-cell;
vertical-align: middle
}
http://css-tricks.com/vertically-center-multi-lined-text/
Was looking at this problem recently, and tried:
HTML:
<body>
<div id="my-div"></div>
</body>
CSS:
#my-div {
position: absolute;
height: 100px;
width: 100px;
left: 50%;
top: 50%;
background: red;
transform: translate(-50%, -50%);
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
}
Here's the Fiddle:
http://jsfiddle.net/sTcp9/6/
It even works when using "width/height: auto", in the place of fixed dimensions. Tested on the latest versions on Firefox, Chrome, and IE (* gasp *).
Using Flexbox:
<style>
.container {
display: flex;
align-items: center; /* Vertical align */
justify-content: center; /* Horizontal align */
}
</style>
<div class="container">
<div class="block"></div>
</div>
Centers block
inside container
vertically (and horizontally).
Browser support: http://caniuse.com/flexbox
There is a simple way to align vertically and horizontally a div in css.
Just put a height to your div and apply this style
.hv-center {
margin: auto;
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
}
Hope this helped.
You can vertically align by setting an element to display: inline-block, then setting vertical-align: middle;
Try this also work perfectly:
html:
<body>
<div id="my-div"></div>
</body>
css:
#my-div {
position: absolute;
height: 100px;
width: 100px;
left: 50%;
top: 50%;
background: red;
display: table-cell;
vertical-align: middle
}