Preom
Preom

Reputation: 1680

margin property %

the w3c specification states

% Specifies a margin in percent of the width of the containing element

I was wondering if this also applied to vertical margins. Initially I thought it didn't, but I had a container div using absolute position and a contained div using static position. the contained div's vertical margin is exactly that of the width html and not the container div, unless I change the contained div's position to absolute as well. Therefore, I was wondering if the margin is affected by the document layout and if it only takes the width of the containing element.

Update:

The changing the position of div2 changes the size.

CSS:

body {
  height:100%;
}

div {
}

#div1
{
  height: 50%;
  background: #333;
  padding:1px;
}

#div2
{
background-color:#000;
height:50%;
//position:static;
position:absolute;
margin:25%;
}

HTML: <div id="div1"><div id ="div2">this</div> </div>

Upvotes: 0

Views: 124

Answers (4)

Chris
Chris

Reputation: 26878

In CSS, percentage values of margins (both vertical and horizontal margins -- as well as padding percentage values) are always calculated relatively to the element's containing box's width. For reference, you can take a look at this paragraph in the CSS2.1 specification: little link.

I hope that helped!

Upvotes: 2

Jukka K. Korpela
Jukka K. Korpela

Reputation: 201538

The CSS 2.1 spec says about margin: “Percentages: refer to width of containing block” (block, not element). The definition of containing block has special rules, but an absolutely positioned container still defines (by its edge) the containing block for a statically positioned child, and my tests conform this. If your tests suggest otherwise, please post your example code.

Upvotes: 0

Jon Hanna
Jon Hanna

Reputation: 113232

Yes. It may seem strange at first, but it has two sensible reasons:

  1. It makes it a lot more like what you are likely to want should you give the same percentage for the horizontal and vertical margins.
  2. If content is flowing within the element, and the container is expanding with it, then the having the vertical margin depend on the vertical size would make it depend upon something which in turn depends on the size of the vertical margin!

Upvotes: 0

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 174957

Yes, even though it may seem counter-intuitive, vertical percentage margins are relative to the width of the containing element, not the height.

Upvotes: 0

Related Questions