0
CODE:
*{
  margin:0px;
  padding:0px;
}
body{
  font-family:sans-serif;
  width:1024px;
  height:700px;
  border:1px solid green;

  //margin:0 auto;

  margin-left:auto;
  margin-right:auto;
  margin-top:auto;
  margin-bottom:auto;
}

1.我期望从四面八方得到一个居中的盒子,但盒子模型的顶部在身体的开头,如果我明确设置margin-top:20px,盒子模型会向下移动,但为什么顶部不会像其他人一样自动对齐。

2.我也没有得到什么自动值“DOES”来实现居中

  1. 在保证金的情况下:0自动;// 0 的单位是什么?px,em 或 pt。
4

3 回答 3

3

Css 中的垂直对齐是一个既有趣又痛苦的话题。这个stackoverflow queston是我见过的关于为什么垂直对齐会如此痛苦的最简洁的解释

至于你的第一个问题,你不能使用边距垂直对齐的原因在下面的引用中解释了。

...文档流和元素高度计算算法的性质使得不可能使用边距在其父元素内垂直居中。每当更改垂直边距值时,都会触发父元素高度重新计算(重排),这反过来又会触发原始元素的重新居中……使其成为无限循环。

至于您的第二个问题,margin auto 通过计算子容器相对于其父容器宽度的宽度来实现水平居中。然后它通过简单的数学运算在子容器的左右两侧添加均匀的边距,强制水平居中。

至于第二个问题 B 部分,

margin: auto与以下相同:

margin-top: auto;
margin-bottom: auto;
margin-right: auto;
margin-left: auto;

其中 asmargin: 0 auto等价于以下内容:

margin-top: 0;
margin-bottom: 0;
margin-right: auto;
margin-left: auto;

实现垂直居中的解决方案

There are some options that you can utilize however to achieve vertical alignment despite the limitations. The easiest is to leverage a table. With tables, one of the few strong points of them is that using the vertical-align property actually behaves as you would expect when enforced inside of a table. So you can do something like the following:

<body>
    <table style="width: 100%; height: 100%">
         <tr>
              <td>
                   <div id="verticallyCenteredContent" style="vertical-align: middle">
                      OMG it's vertically aligned
                   </div>
              <td>
         <tr>
    <table>
<body>

There are two other common methods that I demonstrated in this jsfiddle.

Useful article that demonstrates a number of scenarios and approaches for achieving vertical centering - Vertical Centering with Css

Cheers!

于 2013-07-13T05:49:15.520 回答
0

At first, use css to horizontal centering the "Div". After that is using javascript to centering vertical. See demo on jsfiddle HTML:

<div class="center">Div content</div>

CSS:

.center {
    font-family:sans-serif;
    width:300px;
    height:300px;
    border:1px solid green;
    margin: 0 auto;
    text-align:center;
}

JS (JQuery):

$().ready(function () {
    $(".center").css("margin-top", ($(window).height() - 300) / 2);
});

See demo on jsfiddle

于 2013-07-13T05:57:35.457 回答
0

Here is one more resource on CSS margin issue. http://techslate.net/looking-at-css-margins/

于 2013-07-15T05:48:03.043 回答