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条回答
小情绪 Triste *
2楼-- · 2019-03-11 10:23

This is a handy bookmark for CSS tricks

http://css-discuss.incutio.com/

Contains lots of centering tricks too.

查看更多
倾城 Initia
3楼-- · 2019-03-11 10:27

Stick with Margin: 0 auto; for horizontal alignment; If you need vertical alignment as well use position: absolute; top: 50%; margin-top: -(width/2)px; Be aware though, If your container has more width than your screen a part of it will fall off screen on the left side using the Position: absolute method.

查看更多
倾城 Initia
4楼-- · 2019-03-11 10:30

Try this; don't know if it works in IE, works fine in Fx though. It centers a DIV block on the page using CSS only (no JavaScript), no margin-auto and the text within the DIV block is still left aligned. I'm just trying to find out if vertical-centering could work that way, too, but so far without success.

<html>
<head>
<title>Center Example</title>
<style>
.center {
   clear:both;
   width:100%;
   overflow:hidden;
   position:relative;
}
.center .helper {
   float:left;
   position:relative;
   left:50%;
}
.center .helper .content {
   float:left;
   position:relative;
   right:50%;
   border:thin solid red;
}
</style>
</head>
<body>
<div class="center">
   <div class="helper">
      <div class="content">Centered on the page<br>and left aligned!</div>
   </div>
</div>
</body>
</html> 
查看更多
登录 后发表回答