How do I prevent a div from overflowing above the viewport?

Issue

I have centered a div like this:

<div class="container">
    START
    { lorem }
    END
</div>
.container {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: min(65ch, 95vw);
}

This works:
if there's enough space
But if I shrink the window, I’ll have this:
if there's NOT enough space
Where I can scroll down and see the end, but not scroll up and see the start.
Same thing happens horizontally, I can scroll to right but not to left if there’s not enough X space.

How do I make translate() move the div down a bit to prevent it from overflowing above the page?

Solution

Solution – 1

Just add height to your container, and it will work.

.container {
   -
   -
   -
   -
   -
   height: 100%;
}

Solution – 2 (flex)

Adding following CSS would also solve the issue:

body {
    display: flex;
    justify-content: center;
}

General Solution / Debugging Tricks for CSS

  1. During the use of position absolute / translate property, you need to make sure that you define the height property.

  2. You can always check the box model for your container to debug the issue or at least get some idea of what’s going on or what is the problem source, it helps a lot. Most of the small / medium level problems related to CSS can be solved just by examining the box model.

  3. Always, before start writing your CSS, add following:

* {
    box-sizing: border-box;
}

html, body {
    margin: 0;
    padding: 0;
}

this helps a lot in bigger projects unless you have something else in mind or it also depends on other use-cases, but these are generally preferred by everyone.

  1. For centering your containers, you can also use grid / flex properties which are some of the best ways of alignment in CSS as well.

Answered By – Harsh Shukla

Answer Checked By – Gilberto Lyons (AngularFixing Admin)

Leave a Reply

Your email address will not be published.