I have no experience with javascript, so I would like to know if it is possible to align a paragraph of text so it is placed in the middle of any browser window, using only html and css. Can this be done without js?

If not, how much javascript will I need to know in order to do that?

thank you

Recommended Answers

All 3 Replies

here is someting to get you going

www.w3.org

To my knowledge, there is no valid way to do this using only html and css.

Try using the following script, where paragraphID is the id tag name of the paragraph.
(i.e. <p id="paragraphID">

window.onload   = initPage;
window.onresize = initPage;

function initPage() {
	
  // Get paragraph height
  var paragraph =  document.getElementById('paragraphID');
  var paragraphHeight   = paragraph.offsetHeight;
  
  // Get browser window height
  var windowHeight = getWindowHeight();

  // Set paragraph area on page
  paragraph.style.position = 'absolute';
  paragraph.style.top = ((windowHeight - paragraphHeight) / 2) + 'px';
}

function getWindowHeight() {
  var windowHeight = 0;
	
  if (typeof(window.innerHeight) == 'number')
    windowHeight = window.innerHeight;
  else {
    if (document.documentElement && document.documentElement.clientHeight)
      windowHeight = document.documentElement.clientHeight;
    else {
      if (document.body && document.body.clientHeight)
        windowHeight = document.body.clientHeight; }; };
	
  return windowHeight;
};

Many thanks for posting this script. It is very helpful and works very easily.

I am using this on a page with multiple paragraphs where I'd like the first paragraph to be centered vertically. This script works well for my first paragraph, but I would like my remaining paragraphs to follow underneath (visible after scrolling). Instead, my second paragraph is starting at the very top of the page. How can it continue after the first paragraph block? Thank you again.

Michael

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.