2

I have a CSS like this:

#sidebar {
   float: left;
   margin: 0;
   padding: 0;
   background: #044169;
}
#sidebar-menu {
   height: 100%;
   margin: 0;
   padding: 0;
   background: #CCCCCC;
}

(Call it test.css) and a simple HTML file like this:

<!DOCTYPE html>
<html>
<head>
   <link rel="stylesheet" href="test.css">
</head>
<body>
  <h1>Test</h1>
  <div id="sidebar">
      <div id="sidebar-menu">
          <ul>
             <li>One</li>
          </ul>
      </div>
  </div>
</body>
</html>

I really do not understand why sidebar-menu is 35px high, and sidebar is 51px wide. Shouldn't sidebar-menu be as high as sidebar...?!?

In my head, I think: well, margins are 0, paddings are 0, so the containing element, sidebar-menu, which has height:100% (of the container, I would think), ought to be as big as the container!

I am obviously getting something very wrong...

4

2 回答 2

4

您在 sidebar-menu 元素中有一个未设置样式的无序列表。默认情况下,列表具有边距/填充。添加:

ul {
    margin:0;
    padding:0;
}

现在侧边栏菜单与其容器的大小完全相同。

演示

于 2012-07-24T11:27:20.840 回答
1

除非另有说明,否则父容器 div 会将自身调整为具有绝对大小而非相对大小的最大元素。

divsidebar-menu没有绝对大小,但从其子项(带有文本“One”的无序列表)确定其大小。正因为如此,它sidebar实际上会将自己的大小调整为 35px 高和 51px 宽,然后它的孩子sidebar-menu将填充 100% 的高度和它的孩子的宽度。

于 2012-07-24T11:24:05.273 回答