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

The basic technique for a horizontal centering of an element with a fixed width is:

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

In some cases it can be 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 change element to:

display: inline-block;

and use on parent:

text-align: center;

I additionally reverted text alignment in the child and limit a width of a centered element, complete example:

<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 complicated solution is using a 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 was moved back by a half of its width and its center became left edge of wrapping float which itself was moved to the center of a container. position: relative makes 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

adb(1), admin(1), android(1), anki(1), blog(1), c(1), css(2), cygwin(2), driver(1), emacs(3), fs(1), git(3), gradle(1), hardware(1), hg(2), html(1), interview(13), java(3), js(3), lang(2), lighttpd(1), mobile(1), naming(1), oracle(1), print(1), problem(5), quiz(6), rst(1), security(1), spring(1), sql(2), srs(1), style(1), unit(1), utils(1), vcs(3), web(2), win(2), windows(1)

Archive