Dreams
Dreams

Reputation: 8506

Why I cannot vertical align my p tag?

var window_height = window.screen.height;
var p_height = document.getElementsByTagName("p")[0].clientHeight;
document.getElementsByTagName("p")[0].style.marginTop = (window_height/2) - p_height/2 +  "px";
body {
  background-color: #F0F0F0;
  font-size: 83%;
}

#main {
  width:100%;
  text-align: center;
}

#main p {
  display: block;
  border: 1px red solid;
  margin:0 auto;
}
<div id="main">
    <p>This is my text.</p>
 </div>

What I want is vertical align my p tag dynamically.

So I use JavaScript to get height of my window and <p> tag height then set margin-top of my tag to (window_height/2) - p_height/2 + "px";

However, it seems not work property. Anyone can help?

Upvotes: 0

Views: 51

Answers (1)

Tasos K.
Tasos K.

Reputation: 8087

window.screen.height will give you the height of the user's screen, while you need the height of the browser's viewport.

var verticalAlignPTag = function() {
    var window_height = window.innerHeight;
    var p_height = document.getElementsByTagName("p")[0].clientHeight;
    document.getElementsByTagName("p")[0].style.marginTop = (window_height/2) - p_height/2 +  "px";
};
verticalAlignPTag();

//Optionally, add the same code to run when the window resizes.
window.onresize = verticalAlignPTag;
body {
  background-color: #F0F0F0;
  font-size: 83%;
}

#main {
  width:100%;
  text-align: center;
}

#main p {
  display: block;
  border: 1px red solid;
  margin:0 auto;
}
<div id="main">
    <p>This is my text.</p>
 </div>

Optionally you can run the same code on the window.onresize event so that if the user changes the browser height your <p> will be adjusted accordingly.

I put the code that aligns the <p> tag to a function so that one can easily bind it to the window.onresize event.

Upvotes: 1

Related Questions