Skip to main content

CSS Browser-Compatible Methods for Horizontal/Vertical Centering

Free2015-06-06#CSS#css水平居中#css竖直居中#兼容ie6

Horizontal and vertical centering are common in web pages, but browser compatibility can be tricky. This article summarizes several common centering methods (supporting IE6+).

no_mkd

I. Horizontal Centering

Horizontal Centering of Inline Elements like Text and Images

Set text-align: center; on the parent element. For example: DemoDemo

Horizontal Centering of Block-Level Elements with Fixed Width

Set margin-left: auto; margin-right: auto;. For example: Demo

Horizontal Centering of Block-Level Elements with Uncertain Width

Method 1

Achieve this by leveraging the auto-width calculation characteristic of the table element + margin-left: auto; margin-right: auto;. For example: Demo

Method 2

Set the block-level element to display: inline; and then treat it as an inline element (set text-align: center; on the container). For example:

Method 3

Set float: left;, position: relative;, and left: 50%; on the container; set position: relative; and left: -50%; on the child element. (Optionally add float: left; for horizontal alignment.)

II. Vertical Centering

Vertical Centering of Text, Images, and Block-Level Elements when Parent Height is Uncertain

Set padding-top = padding-bottom on the container. For example: Demo

Vertical Centering of Single-Line Text when Parent Height is Fixed

Setting line-height equal to the container height can achieve this. For example: Demo

Vertical Centering of Multi-Line Text, Images, and Block-Level Elements when Parent Height is Fixed

Method 1

Achieve this using the default vertical-align: middle; of table child elements th/td (set height: 100%; on the table). For example: Demo

Method 2

Use display: table-cell; with vertical-align: middle; and add a CSS hack. For example: Demo

CSS hack for IE6/7; effectiveness is untested.

Comments

No comments yet. Be the first to share your thoughts.

Leave a comment