18

How do I allow a dynamic (changing in height) content area to be vertically centered on the users screen (regardless of screen size), UNTIL it reaches the point where there is only 100px left of free space at the top of the page?

Here's a diagram: enter image description here

I'm not entirely sure whether the solution to this problem will use only CSS or javascript - so all suggestions are welcome.

5
  • Interesting question ! I didn't see any css property that can achieve this. But, maybe it exists. What you can try is to use css and javascript this way. Use css position:relative and js to set top. While DCA.height()+100 <= container.height, set DCA top at (container.height - DCA.height). Otherwise, top is 0, so the DCA will be attached to the top of the container, assuming the container starts at the "Content can't pass this height" line. Let me try in a jsfiddle and edit my post.
    – TCHdvlp
    Nov 14, 2013 at 9:25
  • Interesting, I'll have a go too TCHdvlp. Nov 14, 2013 at 9:34
  • @4M01 I did have a shot at using max-height, but I didn't have any luck! Nov 14, 2013 at 9:36
  • What makes content area height increase? browser viewport width? Nov 14, 2013 at 10:34
  • Hi Alex. The "content area" (blue) div height increases as it is filed with content. Letters for example. Nov 14, 2013 at 11:03

9 Answers 9

8
+50

My solution takes into account that you want your content to be centered on the whole page and not just "in the space below". I used negative margins to achieve this.

See the working example here:

http://jsfiddle.net/WkQzw/5/

HTML:

<div id="container">
    <div id="table">
        <div id="cell">
            <div id="content">Some content</div>
        </div>
    </div>
</div>

CSS:

#container {
    width: 100%;
    height: 100%;
    padding: 100px 0;
    margin-top: -100px;
}
#table {
    display: table;
    width: 100%;
    height: 100%;
    margin-top: 100px;
}
#cell {
    display: table-cell;
    vertical-align: middle;
}
#content {
    background-color: lightblue;
    width: 50%;
    margin: 0 auto;
}

Tested:

  • IE 9 Win7 --> WORKS
  • Chrome 30 Mac --> WORKS
  • Safari 7 Mac --> WORKS
  • Firefox 25 Mac --> WORKS

Update:

I used box-sizing: border-box; but Firefox required an additional -moz-box-sizing: border-box;. Now it works also in Firefox.

2
  • Oooo exciting. Thanks Toni, I'll try it out! Nov 14, 2013 at 11:13
  • Great answer, it worked like a charm. Nice work with your JS Fiddle, too. Nov 14, 2013 at 12:24
6
+50

Pure CSS, not using Table

Another way to approach this would be to use CSS Grids. The align-items property allows you to vertically align grid contents easily, falling back to normal alignment when the content outgrows the cell.

An example:

function removeParagraph() {
  
  const p = document.querySelector('p')
  
  if (p)
    p.parentNode.removeChild(p)
    
}

function addParagraph () {

  const p = document.createElement('p')
  
  p.textContent = 'Bacon ipsum dolor sit amet drumstick rump swine capicola pastrami boudin t-bone, ground round filet mignon andouille frankfurter meatloaf.'
  
  document.querySelector('#content').appendChild(p)

}
html, body {
    
  height: 100%;
  
  margin: 0;
  padding: 0;
    
}

#wrapper {
  
  height: 100%;
  
  display: grid;
    
  grid-template-rows: 50px 1fr;
    
  align-items: center;
  
}

#space {
  
  height: 50px;
  width: 100%;
  
  border-bottom: 2px dashed red;
  
  color: red;
  
  text-align: center;
  
  line-height: 50px;
  
}

#content {
  
  width: 80%;
  
  background-color: lightblue;
  
  margin: 0 auto;

}

p {
  
  padding: 10px;
  margin: 0;

}
<section id="wrapper">
  <div id="space">
     <button onclick="removeParagraph()">remove paragraph</button>
     <button onclick="addParagraph()">add paragraph</button>
  </div>
  <div id="content">
    <p>Bacon ipsum dolor sit amet drumstick rump swine capicola pastrami boudin t-bone, ground round filet mignon andouille frankfurter meatloaf.
    </p>
  </div>
</section>

In the above example I'm using Javascript to allow you to add/remove paragraphs so that you can see the affect of growing the content. This is still a pure CSS solution to the problem.

Depending on your audience, support for CSS grids is pretty good.

1
  • This is awesome @shennan. Any insight on why this doesn't work with flexbox? when I use flex, the content does scroll, but the top portion is clipped off. Oct 15, 2020 at 5:05
4

Pure CSS, Reduced HTML

This is based off of ToniTornado's answer, but with far less wrappers needed.

See fiddle demo

HTML

<div id="container">
      <div id="content">Some content</div>
</div>

CSS (minimum for vertical positioning)

* {
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}

html, body {
    height: 100%;
    margin: 0;
    padding: 0;
}

body {
    display: table;
    padding-top: 100px;
    margin-top: -100px;
}

#container {
    display: table-cell;
    vertical-align: middle;
    padding-top: 100px;
}

Optional Vertical Centering Below Top Area

As the above fiddle showed, the above css centers the #content on the screen space. If you prefer to center on the space left below the top area, then adjust the body by removing the negative top margin and the #container by removing its top padding, like this fiddle and this css shows:

body {
    display: table;
    padding-top: 100px;
}

#container {
    display: table-cell;
    vertical-align: middle;
}
1

Although it requires an additional .wrapper, this layout is doable with display: table; and friends:

html

<div class="container">
    <div class="top">some space</div>
    <div class="wrapper">
        <div class="content">
            <div style="height: [any height]">centered content</div>
        </div>
    </div>
</div>

css

.container {
    display: table;
    width: 100%;
    height: 100%;
}
.top {
    height: 100px;
    display: table-row;
}
.wrapper {
    /* this will take up remaining height (or stretch to content) */
    display: table-row;
}
.content {
    /* because this is displayed as a table cell, the vertical align centers
     * its content (instead of how it usually works on inline elements) */
    display: table-cell;
    vertical-align: middle;
}

http://jsfiddle.net/gLECE/3/

UPDATE

The above will center content between the top 100px and the bottom as opposed to between the viewport top and bottom (a hacky way to do this with css is http://jsfiddle.net/gLECE/6/ but ToniTornado's answer is a solid workaround)

@TCHdvlp's attempt is close, but missing some essential parts (missing top space, and actually not quite centering).

Working, edited version of TCHdvlp's script:

var height = $(document.body).height();
$(".dca").each(function(){
    if(($(this).height()+100) < height){
        $(this).css({top: '50%', marginTop: - $(this).height() / 2 });
    }
});

http://jsfiddle.net/gLECE/6/

Note: you probably want to do this not only on page load, but also when the window is resized.

5
  • Tables are evil, altough in this situation will be they probably unavoidable.
    – peterh
    Nov 14, 2013 at 10:37
  • 3
    @MaXX <table> is considered bad for layout, but there is no reason to avoid display: table;. Even ie8 is supported :)
    – xec
    Nov 14, 2013 at 10:43
  • Yes, but in a <table> (or <div style="display: table">) works the additional positioning buggy, even in the newest browsers. This is because I avoid always the tables, not because the standard.
    – peterh
    Nov 15, 2013 at 20:09
  • @MaXX Sorry, I don't quite understand what you mean by "works the additional positioning buggy"? If you check out the accepted answer, it works a charm (and is using CSS tables, much like in my attempt)
    – xec
    Nov 15, 2013 at 20:23
  • Sorry. I thought at the content of your innermost div. It is not clear, how absolute, relative, etc. positioning works in them, it is not documented and in my experiments I found them buggy and problematic. It is possible, that somebody can figure out, how this works, but it won't be the docs on w3.org.
    – peterh
    Nov 15, 2013 at 22:10
1

A table-less but javascript based solution (just to add variety)

HTML

<div id="container">
    <div id="topbar">You can't touch me</div>
    <div id="content">Aliquam erat volutpat...</div>
</div>

CSS

div#topbar {
    border: 2px dashed red;
    height: 50px;
    text-align: center;
}
div#content {
    background: #90c0ff;
    width: 260px;
    margin: 0px auto;
    position: relative;
}

Javascript

var content = document.getElementById('content');
var topMargin = (window.innerHeight - document.getElementById('topbar').offsetHeight - content.offsetHeight) / 2;
if (topMargin < 0) {
    topMargin = 0;
}
content.style.top = topMargin + 'px';

http://jsfiddle.net/SD7SA/

1
  • Thanks András, I actually prefer this solution to the mess of tables. Nov 15, 2013 at 8:06
0

Interesting question ! I didn't see any css property that can achieve this. But, maybe it exists. What you can try is to use css and javascript this way. Use css position:relative and js to set top. While DCA.height()+100 <= container.height, set DCA top at (container.height - DCA.height). Otherwise, top is 0, so the DCA will be attached to the top of the container, assuming the container starts at the "Content can't pass this height" line. Let me try in a jsfiddle and edit my post.

Here it is :

http://jsfiddle.net/TCHdevlp/gLECE/

4
  • Hmmm, is it possible to achieve it without knowing the actual height of the container? The height within the content box's will vary, so wouldn't the #container have to fluctuate with it? Or would you suggest detecting the screen height of the user and setting that as the #container height? Nov 14, 2013 at 9:46
  • Remember that this is taking place in the entire screen/window. Nov 14, 2013 at 9:46
  • In my exemple, container is a div. I have chosen it as the container. You can chose the window as the entire conainer. As you can see in my example, I have NOT performed my computing like DCAHeight+100 < 500 but I have get container.height. The container size may vary, the result will be good.
    – TCHdvlp
    Nov 14, 2013 at 9:52
  • How come number 3 is higher than number 2, though? Nov 14, 2013 at 10:39
0

Without JS is it possible, but it will be surelly hard, and probably you will need to use a lot of CSS code, which is incompatible with older (<9) IE versions.

The concept were to following:

  1. Position an outer div horizontally and vertically centered (it is hard, if the height of your body isn't fix)
  2. give him a max-height: 100%
  3. In this div create an internal div which is aligned vertically to the top.

If you want, I could to this for you in a jsfiddle.

2
  • Hi MaXX. This makes sense to me, but what's stopping the outer div from expanding upwards when there is only 100px of space left at the top? Nov 14, 2013 at 10:44
  • 1
    Hi Adam. The max-height: 100% will prevent this. The hard thing in this is the vertically middle position if the height of the body isn't known.
    – peterh
    Nov 14, 2013 at 12:38
0

https://playcode.io/1650918

You can achieve this using flex.

Make spacers using the min-height property to keep the flex wrapper centered. Due to the use of margin:auto, the flex wrapper won't pass the top spacer once the content is too big, and min-height will prevent that spacer from shrinking.

This will center the content in the middle of the screen (instead of the middle of the area below the top space). Once the content is too big to fit between the spaces, it will extend past the lower space.

body {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.space {
  min-height: 100px;
  background-color: rgba(0, 0, 0, 0.158);
}

.content-container {
  height: 100%;
  display: flex;
}

.content {
  margin: auto;
  background-color: cyan;
  height: 500px;
  width: 500px;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <link rel="stylesheet" href="src/style.css" />
</head>

<body>
  <div class="space"></div>
  <div class="content-container">
    <div class="content">
      <p>CONTENT</p>
    </div>
  </div>
  <div class="space"></div>
</body>

</html>

-4

Ensure you've enabled html5 declaration by using <!DOCTYPE html>

Thereafter, use the <center style="width:100%;"></center> tag to centralise your element.

Any element within the tag above will be centralised and responsive.

1
  • It doesn't solve the problem of the vertical centralization. (And is against the html5 standard too, although most browser can handle it. A <div style="width: 100%; text-align: center"> were better)
    – peterh
    Nov 15, 2013 at 20:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.