Oleksandr Gavenko's blog
2017-01-28 22:00 Horizontal centering in CSS

Basic technique for horizontal centering of element with fixed width is using:

margin-left: auto;
margin-right: auto;

If possible sometimes it shortened to:

margin: 0 auto;

Complete example:

<style>
  .center {
    width: 780px;
    margin: 0 auto;
  }
</style>

<div class="container">
  <div class="center">...</div>
</div>

Width can be set with width or max-width.

If width of element is unknown we can use on parent:

text-align: center;

and change element to:

display: inline-block;

Complete example (I additionally revert text alignment in child and limit width of centered element):

<style>
  .container {
    text-align: center;
  }
  .center {
    display: inline-block;
    text-align: left;
    max-width: 480px;
  }
</style>

<div class="container">
  <div class="center">...</div>
</div>

A bit harder solution is using float with 50% offset. Working example:

<style>
  .container {
    overflow: hidden;
  }
  .helper {
    position: relative;
    float: left;
    left: 50%;
  }
  .center {
    position: relative;
    left: -50%;
    max-width: 480px;
  }
</style>

<div class="container">
  <div class="helper">
    <div class="center">...</div>
  </div>
</div>

Centered content moved back by a half of its width and its center became left edge of wrapping float which itself moved to the center of container. position: relative keeps possible to specify left offset.

http://stackoverflow.com/questions/283961/centering-a-div-block-without-the-width http://stackoverflow.com/questions/18524722/center-an-auto-width-div

css

Feeds

all / emacs / java / python

Tags

admin(1), anki(1), blog(1), css(2), cygwin(2), emacs(3), fs(1), git(1), hg(2), html(1), interview(11), java(2), js(3), lang(1), lighttpd(1), mobile(1), naming(1), printer(1), problem(5), quiz(6), rst(1), security(1), sql(1), srs(1), unit(1), utils(1), vcs(1), web(2), win(2)

Archive