0

I have been trying to set a text to center of a screen. so i placed a div with some text inside the body directly with some text and added height to it as 50% and margin-top as 50%. I thought it would hold the div's top position always at 50%. But i am wrong.

HTML:

<div id="test">test.. !</div>

CSS:

html, body {
    width:100%;
    height:100%;
    margin:0;
}
div {
    margin-top:50%;  
    text-align:center;
    width:100%;
    height:50%;
}

Do you have any ideas on why it is misbehaving? Please do not suggest any new ideas. I know other ideas for centering it. But I wonder why this snippet is not working.

DEMO

potashin
  • 44,205
  • 11
  • 83
  • 107
Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
  • It is better to use `code snippet` feature of stack overflow instead of providing link to jsfiddle. – niyasc Apr 07 '15 at 12:40

2 Answers2

2

This is primarily a question of "50% in relation to what?"

Setting the height of the div to 50% makes the height 50% of its container, in this case the body element.

Setting the margin-top to 50% then puts a top margin to half the width of the div.

Please see this question on SO for clarification: Why are margin/padding percentages in CSS always calculated against width?

Additionally, the top margin is applied between the parent and the top edge of the div, not the vertical centre.

All these factors play a role in the resulting div not being centered in its container.

Community
  • 1
  • 1
Drenmi
  • 8,492
  • 4
  • 42
  • 51
0

Try This

 html, body {
        width:100%;
        height:100%;
        margin:0;

    }
div {
    width:100%;
    height:50%;
  overflow: auto;
  margin: auto;
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0; 
   right: 0;
    text-align:center;
    border:1px solid black;
}

DEMO-JSFiddle

Kawinesh S K
  • 3,148
  • 1
  • 16
  • 29