This is a premium alert message you can set from Layout! Get Now!

How to prevent overflow scrolling in CSS

0

Have you ever seen a horizontal scroll bar on your screen because your web content did not fit? Have you opened a modal and the rest of the page (the background content) is still scrolling? Have you tested your site with a different browser, yet the page scrolls horizontally?

I am sure you have. Nevertheless, every frontend developer has encountered this problem more often than not. This is the scrolling overflow problem related to our CSS styling.

This article will discuss what an overflow scroll in CSS is, explain what causes this issue, and suggest ways to fix the problem, including:

I think we will have lots of fun while learning it.

What is overflow in CSS?

Before we look at what the overflow property in CSS means, we first need to understand that “everything in CSS is a box.” We resize these boxes to fit our desired design by decreasing or increasing the height and width.

In the image and code below, we will outline our root HTML file in red to better understand what we mean:

* {
  outline: 1px solid red;
}

The Box Outline Of CSS Indicates Headers And Paragraphs Are Inside A Box

The CSS overflow property specifies or controls what should happen to contents that are too large to fit in an element’s box. Content in overflowing boxes is either clipped or hidden, or scrollbars can be added to view the overflowing content.

However, note that the overflow property works only for block elements with a specified height and width.

The overflow property works for both axes, meaning horizontally and vertically.

 

Different Overflow Values

The four boxes above are the four possible values of the overflow property.

Scroll value

The scroll value of the overflow property adds horizontal and vertical scroll bars so you can adjust or scroll the content if it’s too large to fit.

Hidden value

The hidden value ensures the content outside the viewport is hidden and only the part inside the viewport is visible.

Auto value

With the auto value, the content that is not visible in the viewport is hidden, and scroll bars are introduced so the expanded content can fit and be seen.

Visible value

With the visible value, the entire content is displayed, regardless of the height and width of the element’s container.

What causes the overflow scroll issue?

Now that we have seen and understood what the CSS overflow property is, we can examine what causes the scroll problems, specifically horizontal scrolling issues, and how to fix them.

Max viewport width

Viewport width, also known as vw, is one of the units of measurement for length in CSS. Using this unit can sometimes cause problems when scrolling horizontally.

This can happen if you add a width of 100vw to page content, meaning it automatically makes up 100% of the width of the viewport plus the width of the scrollbar.

Be sure to note, however, the scrollbar is always visible to indicate that the content is outside or below the height of the viewport.

CSS 100vw Issue

To fix this problem, avoid using vw for your max-width and use a max-width of 100% instead. This will transfer the width of the parent container to the width of the child container.

CSS grid

The CSS grid can also lead to the horizontal scrolling problem for two reasons:

  1. The use of percentages (%)
  2. Using pixels (px)

Let’s start with using percentages. In a scenario where you want to position four elements horizontally, we can use the CSS grid by writing the following code:

.grid-container {
  display: grid;
  grid-template-columns: repeat(4, 25%)
}

This works well because we give the four elements the same width of 25% (100/4).

CSS Grid Image Without Grid Gap

Furthermore, assuming we want to space the items because they are clustered, we can add a grid-gap of 10px:

.grid-container {
  display: grid;
  grid-template-columns: repeat(4, 25%);
  grid-gap: 10px
}

As a result, horizontal scrolling automatically occurs because the grid-gap value is added to the width, exceeding 100%.

CSS Grid Image After Adding Grid-Gap

The next issue comes when using pixels; similar to the percentage example above, using pixels creates horizontal scrolling issues. For example, imagine you want to apply the same grid to some containers but with pixels, since you want to specify what you want:

.grid-container {
  display: grid;
  grid-template-columns: 1fr 350px 350px 1fr;
  grid-gap: 50px
}

While this won’t cause a scrolling problem on a desktop, it will cause a horizontal scroll issue on any smaller screen, such as on a mobile phone. Why? The pixel width exceeds the mobile viewport width.

So, as a suggestion to fix this issue, avoid using pixels and percentages on smaller screens. Instead, use fractions and a media query on desktop screens to specify your distinct width.

Let’s see how we can utilize this:

.grid-container {
    display: grid;
    grid-template-columns: 1fr;
    grid-gap: 50px;
}
@media (min-width: 600px) {
    .grid-container {
        grid-template-columns: 1fr 350px 350px 1fr;
    }
}

According to the images, it uses the grid-column specified in the media query on desktops and the default grid-column on lesser screens (1fr).

On Desktop Screens

On Mobile Screens

Not wrapping with Flexbox

When using CSS Flexbox, wrapping your flex items is recommended. But if we don’t and view the page on a smaller screen, the flex items may not fit the screen’s viewport, therefore causing the horizontal overflow issue:

.flex-container {
  display: flex;
}

Image Showing Flexbox No Wrap

To solve this, you should always wrap your flex items. By adding the flex-wrap to your flex items, the flex items will align themselves under one another to fit a smaller screen:

.flex-container {
  display: flex;
  flex-wrap: wrap; 
}

Image Showing Flexbox With Flex-Wrap

Using images without max-width

When an image’s width is greater than its parent box or container, the parent box enlarges so the image can fit. This sometimes tends to cause the horizontal scrolling issue.

Image Showing Image Without Max-Width

To fix this issue, simply add a max-width of 100% to the image. This style causes the image to take up the same width as the parent box, thus fitting into the parent container without enlarging it:

image {
  max-width: 100%
}

Image With Max-Width

Debugging the overflow scroll

We have now seen the different scenarios and instances where we can encounter the horizontal scroll problem. We also saw how to fix these issues when we see them, but one thing is still missing.

Imagine you wrote many lines of code before you encounter the overflow scroll issue, and you can’t even tell what the issue is. What do you do? You try to debug the problem.

There are two ways we can fix the problem:

  1. Debugging with CSS
  2. Using Devtools

Debugging with CSS

Debugging with CSS is the most efficient way to get to the issue. To do this, add the outline style to the root of your CSS and see which box or container overlaps and causes the issue.

To debug using CSS, write the code below:

* {
  outline: 1px solid red;
}

From the image below, a red CSS outline can be seen in every box on your website, which you can identify to understand where and what the issue is on your website.

Box Outline Of CSS

Using Devtools

Similarly, you can also use the browser Devtools to debug the horizontal overflow issue. Devtools are a set of web developer tools built into your browser that allow you to test, create, and debug software and websites.

There are different ways to open up the Devtools: You can either right-click on the webpage and click the Inspect option, or press the F12 key, Ctrl+Shift+I, or Ctrl+Shift+C.

You can then debug by deleting the contents of the webpage until you identify the problem. Then you can go to the CSS and make the necessary changes.

Overflow scroll on modals

The issue of the overflow scroll does not only happen with the horizontal scroll but can also happen with modals.

For example, you might open a modal and the background contents continue scrolling. That is not the best user experience you want to offer, and rather the background contents remain fixed when you open the modal.

Image Showing Scrolling Background Content

Below are two ways we can achieve this. The old method was to either set the position to fixed or set the overflow to hidden. This can work but it doesn’t seem to work across all browsers like the Safari browser:

// set body position to fixed
const open = document.querySelector('#open-modal');
const closeModalBtn = document.querySelector('#close');
const modal = document.querySelector('.modal-container');
// Open modal
open.addEventListener('click', () => {
    modal.style.display = 'block';
    document.body.style.position = 'fixed';
});
// Close modal
closeModalBtn.addEventListener('click', () => {
    modal.style.display = 'none';
    document.body.style.position = '';
});

OR

// set body overflow to hidden
const open = document.querySelector('#open-modal');
const closeModalBtn = document.querySelector('#close');
const modal = document.querySelector('.modal-container');
// Open modal
open.addEventListener('click', () => {
    modal.style.display = 'block';
    document.body.style.overflow = 'hidden';
});
// Close modal
closeModalBtn.addEventListener('click', () => {
    modal.style.display = 'none';
    document.body.style.overflow = 'visible';
});

Image Showing Modal With Resolved Scrolling Background Content

Similarly, another way to achieve this is by programmatically adding a new CSS class when the modal is open and removing the class when the modal closes.

Let’s first write the CSS for the class:

.modal-active {
    touch-action: none;
    -webkit-overflow-scrolling: none;
    overflow: hidden;
    overscroll-behavior: none;
}

Then, let’s add the class using JavaScript whenever we open the modal:

const open = document.querySelector('#open-modal');
const closeModalBtn = document.querySelector('#close');
const modal = document.querySelector('.modal-container');
// Open modal
open.addEventListener('click', () => {
    modal.style.display = 'block';
// add modal-active class
    document.body.classList.add('modal-active');
});
// Close modal
closeModalBtn.addEventListener('click', () => {
    modal.style.display = 'none';
// remove modal-active class
    document.body.classList.remove('modal-active');
});

In a scenario where the modal has some contents that are impossible to see, you can add the scroll behavior to the modal so you can scroll down to view the content:

.modal-content {
    overscroll-behavior-y: contain;
    overflow-y: auto;
}

Modal With Overscroll-Behavior

Conclusion

Now we understand the various scenarios and causes of the overflow scroll issue and how to fix these issues.

It is also important to note also that you can always truncate texts and break words when building websites. This is because users can type in lengthy text that may exceed or overflow the container, causing a messy design or the horizontal overflow scroll.

The post How to prevent overflow scrolling in CSS appeared first on LogRocket Blog.



from LogRocket Blog https://ift.tt/Kn7Cuq8
via Read more

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment

Search This Blog

To Top