Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Align vertically using CSS 3

With CSS 3, are there any way to vertically align an block element? Do you have an example? Thank you.

like image 252
tho Avatar asked Mar 23 '11 23:03

tho


People also ask

How do I align vertically in CSS?

CSS Demo: vertical-align The vertical-align property can be used in two contexts: To vertically align an inline element's box inside its containing line box. For example, it could be used to vertically position an image in a line of text. To vertically align the content of a cell in a table.

How do I align content vertically?

The CSS just sizes the div, vertically center aligns the span by setting the div's line-height equal to its height, and makes the span an inline-block with vertical-align: middle. Then it sets the line-height back to normal for the span, so its contents will flow naturally inside the block.

How do I align vertically in HTML?

For vertical alignment, set the parent element's width / height to 100% and add display: table . Then for the child element, change the display to table-cell and add vertical-align: middle . For horizontal centering, you could either add text-align: center to center the text and any other inline children elements.


2 Answers

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 *).

like image 180
Charlie Avatar answered Sep 28 '22 01:09

Charlie


Note: This example uses the draft version of the Flexible Box Layout Module. It has been superseded by the incompatible modern specification.

Center the child elements of a div box by using the box-align and box-pack properties together.

Example:

div { width:350px; height:100px; border:1px solid black;  /* Internet Explorer 10 */ display:-ms-flexbox; -ms-flex-pack:center; -ms-flex-align:center;  /* Firefox */ display:-moz-box; -moz-box-pack:center; -moz-box-align:center;  /* Safari, Opera, and Chrome */ display:-webkit-box; -webkit-box-pack:center; -webkit-box-align:center;  /* W3C */ display:box; box-pack:center; box-align:center; }  
like image 39
Crashalot Avatar answered Sep 28 '22 02:09

Crashalot