今天看到了一个特别的绝对居中的方法,很有创意,记录下来。原博客地址http://codepen.io/shshaw/full/gEiDt。
这种方法唯一的缺点就是需要父元素指定高度,但是它可以用min/max-height来所响应式设计。
如果以上连接可以打开就看上面的连接,如果连接失效了才看下面的复制出来的内容。
Absolute Centering in CSS
Thanks for the positive comments! Now you can read this article on Smashing Magazine and experience a few new demos (likeResizing) and code examples (Other Techniques) below! Leave a comment on CodePen, Smashing Magazine, or message@shshaw on Twitter if you find any additional features or have additional suggestions.
We've all seen margin: 0 auto;
for horizontal centering, but margin: auto;
has refused to work for vertical centering... until now!
Spoiler alert: Absolute Centering only requires a declared height and these styles:
.Absolute-Center { margin: auto; position: absolute; top: 0; left: 0; bottom: 0; right: 0; }
I'm not the pioneer of this method (yet I have dared to name it Absolute Centering), and it may even be a common technique, however, most vertical centering articles never mention it and I had never seen it until I dug through the comments section of a particular article.
There, Simon linked to this jsFiddle that blew every other method out of the water (the same method was also mentioned by Priit in the comments). Researching further, I had to use very specific keywords to find some othersources for this method.
Having never used this technique before, I put it to the test and discovered how incredible Absolute Centering really is.
Advantages:
- Cross-browser (including IE8-10 without hacks!)
- No special markup, minimal styles
- Responsive with percentages and min-/max-
- Centered regardless of padding (without
box-sizing
!) - Blocks can easily be resized
- Works great on images
Caveats:
- Height must be declared (see Variable Height)
- Recommend setting
overflow: auto
to prevent content spillover (see Overflow) - Doesn't work on Windows Phone
Browser Compatibility:
Chrome, Firefox, Safari, Mobile Safari, IE8-10.
Absolute Centering was tested and works flawlessly in the latest versions of Chrome, Firefox, Safari, Mobile Safari, and even IE8-10.
One user reported that the content is not vertically centered in Windows Phone's browser, but otherwise this technique works as expected.
If you find any additional features or issues, leave a comment in CodePen or tweet to @shshaw!
Within Container
Place your content block inside of a position: relative
container to perfectly center your content within the container!
.Absolute-Center { 50%; height: 50%; overflow: auto; margin: auto; position: absolute; top: 0; left: 0; bottom: 0; right: 0; }
Absolute Center,
Within Container.
This box is absolutely centered, horizontally and vertically, within its container using position: relative
Within Viewport
Set your content block to position: fixed
and give it a z-index, like the modal on this page, to keep it centered in the viewport.
- Mobile Safari: The content block will be centered vertically in the whole document, not the viewport, if it is not within a
position: relative
container.
.Absolute-Center.is-Fixed { 50%; height: 50%; overflow: auto; margin: auto; position: fixed; top: 0; left: 0; bottom: 0; right: 0; z-index: 999; }
Responsive
Perhaps the best benefit of Absolute Centering is percentage based width/heights work perfectly! Even min-width/max-width
and min-height/max-height
styles behave as expected for more responsive boxes.
Go ahead, add padding to the element; Absolute Centering doesn't mind!
.Absolute-Center.is-Responsive { 60%; height: 60%; min- 400px; max- 500px; padding: 40px; overflow: auto; margin: auto; position: absolute; top: 0; left: 0; bottom: 0; right: 0; }
Absolute Center,
Percentage Based.
This box is absolutely centered, horizontally and vertically, even with percentage based widths & height, min-/max-, and padding!
Offsets
If you have a fixed header or need to add other offsets, simply add it in your content block's styles like top: 70px;
. As long as margin: auto;
is declared, the content block will be vertically centered within the bounds you declare withtop
left
bottom
and right
You can also stick your content block to the right or left while keeping it vertically centered, using right: 0; left: auto;
to stick to the right or left: 0; right: auto;
to stick to the left.
.Absolute-Center.is-Right { 50%; height: 50%; margin: auto; overflow: auto; position: absolute; top: 0; left: auto; bottom: 0; right: 20px; text-align: right; }
Vertical Center,
Align Right.
This box is absolutely centered vertically within its container, but stuck to the right with right: 0; left: auto;
Overflow
Content taller than the block or container (viewport or a position: relative
container) will overflow and may spill outside the content block and container or even be cut off. Simply adding overflow: auto
will allow the content to scroll within the block as long as the content block itself isn't taller than its container (perhaps by adding max-height: 100%;
if you don't have any padding on the content block itself).
.Absolute-Center.is-Overflow { 50%; height: 300px; max-height: 100%; margin: auto; overflow: auto; position: absolute; top: 0; left: 0; bottom: 0; right: 0; }
Absolute Center,
With Overflow.
This box is absolutely centered within its container, with content set to overflow.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent bibendum, lorem vel tincidunt imperdiet, nibh elit laoreet felis, a bibendum nisl tortor non orci. Donec pretium fermentum felis, quis aliquet est rutrum ut. Integer quis massa ut lacus viverra pharetra in eu lacus. Aliquam tempus odio adipiscing diam pellentesque rhoncus. Curabitur a bibendum est. Mauris vehicula cursus risus id luctus. Curabitur accumsan venenatis nibh, non egestas ipsum vulputate ac. Vivamus consectetur dolor sit amet enim aliquet eu scelerisque ipsum hendrerit. Donec lobortis suscipit vestibulum. Nullam luctus pellentesque risus in ullamcorper. Nam neque nunc, mattis vitae ornare ut, feugiat a erat. Ut tempus iaculis augue vel pellentesque.
Vestibulum nunc massa, gravida quis porta nec, feugiat id metus. Nunc ac arcu dolor, quis vestibulum leo. Cras viverra mollis ipsum, non rhoncus lectus aliquam et. Morbi faucibus purus sit amet lacus aliquet elementum. Donec sit amet posuere enim. Cras in eros id tortor fringilla ultricies. Mauris faucibus ullamcorper velit, pulvinar varius odio eleifend eu. Quisque id odio metus. Morbi adipiscing ultricies posuere. Pellentesque elementum porttitor eros in molestie. Maecenas ut leo quis nisi tempor tincidunt.
Resizing
You can resize your content block with other classes or Javascript without having to recalculate the center manually! Adding the resize
property will even let your content block be resized by the user.
Absolute Centering keeps the block centered no matter how the block is resized. Setting min-/max- will limit the block's size to what you want and prevent it from overflowing the window/container.
If you don't use resize: both
, you can add a transition
to smoothly animate between sizes. Be sure to setoverflow: auto
since the block could be resized smaller than the content.
- Set your
max-width/max-height
to compensate for any padding on the content block itself, otherwise it will overflow its container. - The
resize
property is not supported on mobile browsers or in IE 8-10 so make sure your users have an alternate way of resizing if that is essential to user experience. - Combining
resize
andtransition
properties causes a delay equal to the transition time when the user attempts to resize.
.Absolute-Center.is-Resizable { min- 20%; max- 80%; min-height: 20%; max-height: 80%; resize: both; overflow: auto; margin: auto; position: absolute; top: 0; left: 0; bottom: 0; right: 0; }
Absolute Center,
Resizable.
This box is absolutely centered within its container and can be resized by the user or via Javascript.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent bibendum, lorem vel tincidunt imperdiet, nibh elit laoreet felis, a bibendum nisl tortor non orci. Donec pretium fermentum felis, quis aliquet est rutrum ut. Integer quis massa ut lacus viverra pharetra in eu lacus. Aliquam tempus odio adipiscing diam pellentesque rhoncus. Curabitur a bibendum est. Mauris vehicula cursus risus id luctus. Curabitur accumsan venenatis nibh, non egestas ipsum vulputate ac. Vivamus consectetur dolor sit amet enim aliquet eu scelerisque ipsum hendrerit. Donec lobortis suscipit vestibulum. Nullam luctus pellentesque risus in ullamcorper. Nam neque nunc, mattis vitae ornare ut, feugiat a erat. Ut tempus iaculis augue vel pellentesque.
Images
Images work too! Apply the class/style to the image itself and set height: auto;
like you would with a responsively-sized image to let it resize with the container.
Note that height: auto;
works for images, but causes a regular content block to stretch to fill the container unless you use the variable height technique. It's likely that because browsers have to calculate the height for the image rendered image, so margin: auto;
ends up working as if you'd declared the height in all tested browsers.
.Absolute-Center.is-Image { 50%; height: auto; margin: auto; position: absolute; top: 0; left: 0; bottom: 0; right: 0; }
Variable Height
Absolute Centering does require a declared height, however the height can be percentage based and controlled bymax-height
. This makes it ideal for responsive scenarios, just make sure you set an appropriate overflow.
One way around the declared height is adding display: table
, centering the content block regardless of content length.
- Firefox/IE8: Using
display: table
aligns the content block to the top, but is still centered horizontally. - IE9/10: Using
display: table
aligns the content block to the top left. - Mobile Safari: The content block is centered vertically, but becomes slightly off-center horizontally when using percentage based widths.
.Absolute-Center.is-Variable { display: table; 50%; overflow: auto; margin: auto; position: absolute; top: 0; left: 0; bottom: 0; right: 0; }
Absolute Center,
Variable Height.
This box is absolutely centered vertically within its container, regardless of content height.
Other Techniques
Absolute Centering works really well for many cases, but there are other methods that may fit more specific needs. The most commonly recommended methods are Negative Margins, Transforms, Table-Cell, and now Flexbox. These techniques are covered more in depth in other articles, so I'll only go over the basics here.
.is-Negative { 300px; height: 200px; padding: 20px; position: absolute; top: 50%; left: 50%; margin-left: -170px; /* (width + padding)/2 */ margin-top: -120px; /* (height + padding)/2 */ }
Negative Margins
Perhaps the most common technique. If exact dimensions are known, setting a negative margin equal to half the width/height (plus padding, if not using box-sizing: border-box
) along withtop: 50%; left: 50%;
will center the block within a container.
- Works well cross-browser
- Requires minimal code
- Not responsive. Doesn't work for percentage based dimensions and can't set min-/max-
- Content can overflow the container
- Have to compensate for
padding
or usebox-sizing: border-box
Absolute Center,
Negative Margins.
This box is absolutely centered vertically within its container using negative margins.
.is-Transformed { 50%; margin: auto; position: absolute; top: 50%; left: 50%; -webkit-transform: translate(-50%,-50%); -ms-transform: translate(-50%,-50%); transform: translate(-50%,-50%); }
Transforms
One of the simplest techniques with about the same benefits as Absolute Centering, but supports variable height. Give the content block transform: translate(-50%,-50%)
with the required vendor prefixes along with top: 50%; left: 50%;
to get it centered.
- Variable height content
- Requires minimal code
- Won't work in IE8
- Need vendor prefixes
- Can interfere with other
transform
effects - Results in blurry rendering of edges and text in some cases
Read more about Transform Centering
Absolute Center,
Translate(-50%,-50%).
This box is absolutely centered vertically within its container using translate(-50%,-50%)
.
<div class="Container is-Table"> <div class="Table-Cell"> <div class="Center-Block"> <!-- CONTENT --> </div> </div> </div>Styles:
.Container.is-Table { display: table; } .is-Table .Table-Cell { display: table-cell; vertical-align: middle; } .is-Table .Center-Block { 50%; margin: 0 auto; }
Table-Cell
This may be the best technique overall, simply because the height can vary with the content and browser support is great. The main disadvantage is the extra markup, requiring a total of three elements to get the final one centered.
- Variable height content
- Content overflows appropriately
- Works well cross-browser
- Requires extra markup
Read more about Table-Cell Centering
Absolute Center,
Table/Table-Cell.
This box is absolutely centered vertically within itsdisplay: table-cell
parent, which is within a display: table
container.
.Container.is-Flexbox { display: -webkit-box; display: -moz-box; display: -ms-flexbox; display: -webkit-flex; display: flex; -webkit-box-align: center; -moz-box-align: center; -ms-flex-align: center; -webkit-align-items: center; align-items: center; -webkit-box-pack: center; -moz-box-pack: center; -ms-flex-pack: center; -webkit-justify-content: center; justify-content: center; }
Flexbox
The future of layout in CSS, Flexbox is the latest CSS spec designed to solve common layout problems such as vertical centering. Smashing Magazine already has a great article onCentering Elements with Flexbox that you should read to for a more complete overview. Keep in mind that Flexbox is more than just a way to center, it can be used for columns and all sorts of crazy layout problems.
- Content can be any width or height, even overflows gracefully
- Can be used for more advanced layout techniques.
- No IE8-9 support
- Requires a container or styles on the body
- Requires many vendor prefixes with different syntaxes to work on modern browsers
- Possible performance issues
Absolute Center,
Flexbox.
This Flexbox box is absolutely centered vertically within its container.
Recommendations
Each technique has their advantages. Which one you choose mainly boils down to which browsers you support and what your existing structure looks like.
Absolute Centering works great as a simple drop-in solution with no-fuss. Anywhere you used Negative Marginsbefore, use Absolute Centering instead. You won't have to deal with pesky math for the margins or extra markup, and you'll be able to size your boxes responsively.
If you need variable height content cross-browser, try out the Table-Cell or Flexbox techniques to see what works best for your site.