-1

In my code you can see that if you add enough elements, some of the content goes off the screen. I'm fine with the content going off the bottom of the screen, because it is still accessible. I don't want it to go off the top of the screen because then you can't access some of the elements.

Is this possible with pure CSS (without using JavaScript)?

Before:

Before

After:

After

function add() {
  items = document.getElementById("items");
  input = document.getElementById("input").value;
  x = document.createElement("p");
  x.innerHTML = input;
  items.appendChild(x);
}
html,
body {
  margin: 0;
  height: 100%;
}

.centered {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
<body class="centered" id="items">
  <h1>TODO:</h1>
  <input type="text" placeholder="Enter Items Here" id="input" />
  <input type="button" onclick="add();" value="add" />
  
  <p>Paragraph.</p>
  <p>Paragraph.</p>
  <p>Paragraph.</p>
  <p>Paragraph.</p>
  <p>Paragraph.</p>
  <p>Paragraph.</p>
  <p>Paragraph.</p>
  <p>Paragraph.</p>
  <p>Paragraph.</p>
  <p>Paragraph.</p>
</body>
isherwood
  • 58,414
  • 16
  • 114
  • 157

2 Answers2

0

Try changing the height to max-height on yor body's css, like this:

html, body {
  /* ... */
  max-height: 100%;
}

This will limit the body's height to 100% of the viewport (i suppose it's viewport) then the overflowing elements will be accessible by scrolling.

And this will also put your input form to the top of the screen, I didn't think of a way to do this without putting it on top

0

I'd usually create containers and set overflow on them and the body, as needed.

Other tips:

  • Use let or const when initializing values to keep their scope appropriate.
  • Give values semantic names. x means nothing to your future self or another developer.

function add() {
  const itemsEl = document.getElementById("items");
  const inputVal = document.getElementById("itemInput").value;

  const paragraphEl = document.createElement("p");
  paragraphEl.innerHTML = inputVal;

  itemsEl.appendChild(paragraphEl);
}
html,
body {
  margin: 0;
  height: 100%;
  overflow: hidden;
}

.centered {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}

.item-wrapper {
  width: 100%;
  text-align: center;
  overflow: auto;
}
<body class="centered">
  <div class="form">
    <h1>TODO:</h1>
    <input type="text" placeholder="Enter Items Here" id="itemInput" />
    <input type="button" onclick="add();" value="add" />
  </div>

  <div id="items" class="item-wrapper"></div>
</body>
isherwood
  • 58,414
  • 16
  • 114
  • 157