Sammdahamm
Sammdahamm

Reputation: 11

HTML parents - Unsure of how to use CSS percentages properly

I'm having a problem with understanding how to properly use the percentage height property in CSS. It has been a useful tool for me in the past, when sizing elements with respect to the page size.

However I have come across a problem when using percentages to specify properties of divs within divs.

For example,

<div class="outer">
  <div class="inner">
     Hello
  </div>
</div

In the above code, I set the text of the "inner" class to have a top-margin of 5%, which successfully pushes the text down from the top edge of the "outer" class.

However, I was told that the 5% would be relative to the parent of the element, which I would assume would be "outer" (because it is within the outer div tags). It actually acts as 5% of the page height, which pushes it down much further than intended.

I'm probably missing some quirk of HTML/CSS, because I'm still relatively new to this, so any help would be appreciated.

Thanks in advance :)

edit: I now understand that the problem lies on certain parent elements not having static dimensions, however is there a way to avoid this but still have relative heights/widths on child elements? It would seem silly to define the body with a static height/width, which would just seriously limit the site's accessibility on devices with other dimensions.

Relevant CSS code for "outer" (bear in mind I just used outer/inner as examples, and below is the actual code I've been using)

.login_center_panel
{
   width:50%;
   height:30%;
   background-color:#3D3D3D;
   margin-left:auto;
   margin-right:auto;
   float:top;
   border-top-left-radius: 15px;
   border-top-right-radius: 15px;
   border-bottom-left-radius: 15px;
   border-bottom-right-radius: 15px;
   font-family: "Verdana", Arial, sans-serrif;
   color:white;
   padding:1px;
}

and below is the relevant css for "inner"

#signinGreetText
{
   margin-top:5%;
}

The margin-top property of signinGreetText still acts as 5% of the whole page, and not as 5% of the height of login_center_panel

Upvotes: 1

Views: 74

Answers (2)

Matt Healey
Matt Healey

Reputation: 172

The % is based on the width of the containing element. You need to specify a width or max-width property for your .outer div or use a different measurement for your top margin. To see how the % is based on the width change the width of the page while viewing your current code. The top margin should change with the width of the page.

Upvotes: 2

Alan Dunning
Alan Dunning

Reputation: 1351

Do you have a height set for 'outer'? If not, this is why the margin is bigger than you expected. If you set a height for 'outer' you will notice the margin will scale accordingly.

Upvotes: 0

Related Questions