Skip to content

Instantly share code, notes, and snippets.

@nicon-dev
Last active June 12, 2016 13:55
Show Gist options
  • Save nicon-dev/0893e32289ea5b95290e to your computer and use it in GitHub Desktop.
Save nicon-dev/0893e32289ea5b95290e to your computer and use it in GitHub Desktop.
CSS - centering techniques
/*1. center a div with margin: 0
- The element must display: block
- The element must not float
- The element must not have a fixed or absolute position
- The element must have a width that is not auto
2. Horizontal and vertical centering if the widths are dynamic:
*/
/* This parent can be any width and height */
.block {
text-align: center;
}
/* The ghost, nudged to maintain perfect centering */
.block:before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
margin-right: -0.25em; /* Adjusts for spacing */
}
/* The element to be centered, can
also be of any width and height */
.centered {
display: inline-block;
vertical-align: middle;
width: 300px;
}
/*
See: http://css-tricks.com/centering-in-the-unknown/
3. Vertical centering with table-cell:
"[...] The trick is to specify that the outer block is to be formatted as a table cell, because the contents of a table cell can be centered vertically."
*/
DIV.container {
min-height: 10em;
display: table-cell;
vertical-align: middle
}
/*
See: http://www.w3.org/Style/Examples/007/center.en.html
3.1 vertical centering with transform (work reayll well)
*/
DIV.container {
position: absolute;
top: 50%;
left: 50%;
margin-right: -50%;
transform: translate(-50%, -50%)
}
/*
See: http://stackoverflow.com/a/28918018/989275
4. Center a image:
"[...] you should explicitly tell the browser that the image is a block element. Then you can center it as you would a block"
*/
img.center {
display: block;
margin-left: auto;
margin-right: auto;
}
/*
See: http://webdesign.about.com/od/beginningcss/a/aa012207.htm
5. Center floating divs:
"You can wrap your floated divs with an inline-block element and center it within its parent."
#main {width: 600px; background-color: #eee; margin: 0 auto; padding: 10px; text-align: center;}
#main .item {float: left; border: 1px solid #ccc; margin: 5px; }
*/
.wrap {
display: inline-block;
margin: auto;
}
/*
See: http://stackoverflow.com/questions/8901209/how-to-center-floating-divs
or this fiddle: http://jsfiddle.net/nvpXx/3/
5.1 center floating divs without inline-block:
See this blog post: http://matthewjamestaylor.com/blog/beautiful-css-centered-menus-no-hacks-full-cross-browser-support
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment