CSS centering tricks [closed]

2019-03-11 09:29发布

My favorite equation for centering an xhtml element using only CSS is as follows:

display: block;
position: absolute;
width: _insert width here_;
left: 50%;
margin-left: _insert width divided by two & multiplied by negative one here_

There's also the simpler margin:auto method in browsers that support it. Does anyone else have tricky ways to force content to display centered in its container? (bonus points for vertical centering)

edit - oops, forgot the 'negative' part of one in the margin-left. fixed.

9条回答
Fickle 薄情
2楼-- · 2019-03-11 10:05
body {
    text-align: center;
}
#container {
    width: 770px;
    margin: 0 auto;
    text-align: left;
}

This works nicely in all the usual browsers. As already mentioned margin: 0 auto; won't work in all semi-current versions of IE.

查看更多
贼婆χ
3楼-- · 2019-03-11 10:07

The absolute positioning with 50% approach has the severe side effect that if the browser window is narrower then the element then some of the content will appear off the left side of the browser - with no way to scroll to it.

Stick to auto margins - they are far more reliable.

If you are working in Standards mode (which you should be) then they are supported in all the browsers you are likely to care about.

You can use the text-align hack if you really need to support Internet Explorer 5.5 and earlier.

查看更多
Rolldiameter
4楼-- · 2019-03-11 10:17

just a note that the margin:auto; method only works if the browser can calculate the width of the item to be centered and the width of the parent container. in many cases setting width:auto; works, but in some it does not.

查看更多
劫难
5楼-- · 2019-03-11 10:20

Well that seems like massive overkill, I've got to say. I tend to set the container to text-align:center; for old browsers, margin:auto; for modern browsers, and leave it like that. Then reset text-align in the element (if it contains text).

Of course, some things need setting as block, and widths need setting... But what on earth are you trying to style that needs that much hacking around?

<div style="text-align:center">
     <div style="width:30px; margin:auto; text-align:left">
         <!-- this div is sitting in the middle of the other -->
     </div>
</div>
查看更多
我想做一个坏孩纸
6楼-- · 2019-03-11 10:20

Margin:auto works in all browsers as long as you make sure IE is in standards mode.

It's more picky than others and requires your doctype to be the very first in your document, which means no whitespace (space, tabs or linefeeds) before it.

If you do that, margin:auto is the way to go! :)

查看更多
The star\"
7楼-- · 2019-03-11 10:23
div #centered{
 margin: 0 auto;
}

seems to be the most reliable from my experience.

查看更多
登录 后发表回答