Merc
Merc

Reputation: 17067

Figuring out heights in CSS

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...

Upvotes: 2

Views: 90

Answers (2)

JJJ
JJJ

Reputation: 33163

You have an unordered list inside the sidebar-menu element which hasn't been styled. Lists have margins/paddings by default. Add:

ul {
    margin:0;
    padding:0;
}

Now the sidebar-menu is exactly the same size as its container.

Demo

Upvotes: 4

maple_shaft
maple_shaft

Reputation: 10463

Unless otherwise specified, the parent container div will size itself appropriately to its largest element that has an absolute size, not a relative size.

The div sidebar-menu does not have an absolute size, but determines its size from its child, the unordered list with the text "One". It is because of this that sidebar will in fact size itself to 35px high and 51px wide, then its child sidebar-menu will fill 100% of that height and the width of its child.

Upvotes: 1

Related Questions