Centering Block Element

From CSS Discuss

Jump to: navigation, search

Contents

Centering Block Element

There are three ways of centering a block:

  1. Centering with margins
  2. Centering with percentages
  3. Centering with absolute sizes.

The first method seems to work better for most.

There are multiple techniques for centering a block element; and the choice for the technique depends on whether you have the size set in percentages or in more absolute values.

Note: If an element fills the width of the screen along the axis you wish to center it along, then centering it will have no effect. Elements with display: block; default to width: auto; and fill the width of the screen, so set an explicit width on them.

Centering with auto-margins

This is a simple method of horizontal CSS centering that works well for block-level elements with either absolute or percentage widths.

It is based on the rule in the CSS2 Visual formatting model details stating that if both margin-left and margin-right are 'auto', their computed values are equal.

Internet Explorer note: Centering block elements by auto-margins only works starting from version 6 and only when in "standard compliant" mode, see IE6 CSS enhancements. Further limitations pertinent to IE are mentioned in the following subsections.

Centering an entire page's contents

The technique is particularly useful when you want to center an entire page's contents. Unlike the 'Centering with absolute sizes' method below, this method should prevent negative left margins from making the left-hand area of the element inaccessible in narrower browser windows.

Internet Explorer note: This centering does not work for Internet Explorer 5.5 or earlier but a workaround exists as IE will accept text-align: center; on a block level element and center it, even though this is incorrect.

Example

This code will center an entire page's contents when contained within a 'wrapper' div 500 pixels wide:

Uncommented example:

body {
  text-align: center;
  min-width: 500px;
}
#wrapper {
  text-align: left;
  width: 500px;
  margin-left: auto;
  margin-right: auto;
}

Commented example:

body {
  text-align: center;  /* MSIE 5 doesn't center based on auto left/right margins, 
                          but 'text-align:center' does center top-level divs: */
  min-width: 500px;      /* Specify a min-width for the body as wide as the 'wrapper'
                           element itself. This prevents negative (i.e. inaccessible)
                           left-margins in narrow browser windows when using 
                           Navigator 6+/Mozilla on Win32: */
}
#wrapper {
  text-align: left;    /* Reset alignment to compensate for 'text-align:center': */
  width: 500px;        /* Specify the width of the element. This should be the same
                          as 'body min-width': */
  margin-left: auto;   /* Set left and right margins to auto, thus centering the 
                          element in the containing (body) tag: */
  margin-right: auto;
}

see also: Centering: Auto-width Margins

Centering an absolutely positioned element

Auto-margins can center an absolutely positioned element inside its containing block.

For this to work, you have to

  1. specify the offset properties (of opposite sides) with same values, i.e. by setting left:0; right:0; for horizontal centering and top:0; bottom:0; for vertical centering,
  2. set dimensions along the axis you want to center along,
  3. enable auto-margins along the axis you want to center along.

Internet Explorer note: IE can not relate absolutely positioned elements to opposite sides of containing block, so only one of the offset properties is used. This brings the element out of balance and renders auto-margins useless. A workaround is use relative positioning for the element to be centered and wrap it with an absolutely positioned element with top, left and right set to 0.

Example

These CSS definitions will horizontally center a DIV of class center inside its container DIV of class container on most browsers except Internet Explorer.

.container {
  position: relative;       /* make this a containing block! */
  border: 1px dotted red;   /* mark this element visually prominent */
}
.center {
  position: absolute;       /* take element out of the normal page flow! */
  top: 10px;                /* position the element vertically using top or bottom
                               and define width as you like:*/
  width: 50%;   
  left: 0;                  /* set left and right to the same value! */
  right: 0;
  margin-left: auto;        /* adding auto-margins left and right will
                               center the element horizontally!*/
  margin-right: auto;
  background:red;           /* mark this element visually prominent */
}

A Mac/IE Bug centering tables

If you are trying to center a table using this method, keep in mind that you must use the longhand margin properties (e.g. margin-left, as shown above) if you want it to work in Mac/IE. The shorthand margin: 0 auto; will work for other blocks in Mac/IE, but not for tables.

Table centering using CSS or HTML

Centering with percentages

This is the simplest centering method. The following example is for horizontal centering, but you can apply the same logic to the vertical centering.

You know the width of the block you want to center; say 40%. If you want to center this block, you need to position this block half the space that's left from the edges, which means you have to move the block (100%-40%)/2 = 60%/2 = 30% from the left (or the right if you prefer).

Example

Centering a block with a width of 60% and a height of 30%:

.centerblock {
  position: absolute;
  width: 60%;
  height: 30%;
  left: 20%;
  top: 35%;
}

Centering with absolute sizes

This is a little bit more sophisticated. I'll be explaining it for horizontal centering, but again, it's the same for the vertical centering.

You need to have a fixed width for your block in e.g. px; say 300px. Now you move this box 50% to the left, so that the left side of the box will be in the center. The trick with this centering method is that you use negative margin's to 'move the box' in the opposite direction. You move the block half the width of the block this way. In this case this means you need to set margin-left to -(300px/2) = -150px;

Example

Of course, this trick will get an example too. Let's assume you want to center a box width the following dimensions; height: 350px; width: 280px;.

.centerblockabsolute {
  position: absolute;
  width: 280px;
  height: 350px;
  left: 50%;
  top: 50%;
  margin-left: -140px;
  margin-top: -175px;
}

When you don't know the width

If you want to "shrink wrap" (to add borders or something like that) an image (or other block element) without knowledge of its width in the CSS, and you also have small captions, and then you want center the whole thing.

Instead of using a float, you could use a container with display: table/table-cell;. This gives you the shrink-wrap effect and can be horizontally centered with auto margins.

It doesn't work in IE (neither on Windows nor Mac.) For these you could try display: inline-block with conditional comments, which should give the shrink wrap effect, and can be centered inside a container with text-align: center (see previous section).

This method is discussed here:

http://www.solstice.co.il/2008-02-26/horizontally_centering_content_with_dynamic_width_in_css

If you are not happy with display: inline-block or display: table/table-cell (not supported by all browsers) you can center a left-floated block (such as a menu) by relative positioning.

This method is discussed here:

http://matthewjamestaylor.com/blog/beautiful-css-centered-menus-no-hacks-full-cross-browser-support

Alternatively, you can use Javascript to do the same thing, only a bit less elegant: In IE ( Java Script active) you can use Dynamic Properties, provided that you have two containers (one outer and one that is centered):

.centerblock {
 margin-left: expression
  (this.offsetWidth < this.parentNode.offsetWidth ? parseInt
    ((this.parentNode.offsetWidth - this.offsetWidth)/2)+"px":"0");}

The display: table; trick is known to work in Opera, Safari and Mozilla/Firefox. (courtesy of CSS-Discuss)

Another drawback is that any floated DIVs contained within the display:table block will collapse into each other. (unless someone has a fix?)


Vertical Centering

Vertical Centering of element of Known height

http://www.hicksdesign.co.uk/journal/vertical--horizontal-centering-2
http://vmalek.murphy.cz/
http://www.student.oulu.fi/~laurirai/www/css/middle/
http://phrogz.net/CSS/vertical-align/index.html
http://phrogz.net/CSS/valign_in_body/content.html
http://stilbuero.de/demo/vertical_centering.html
http://d-graff.de/fricca/center.html

Vertical Centering of element of Unknown height

http://www.jakpsatweb.cz/css/css-vertical-center-solution.html
http://brunildo.org/test/shrink_center_4.html
http://www.sunburnt.com.au/publications/design/center-multiple-lines-with-css

css basic examples

http://www.csscentering.com

Personal tools