Ilimkan Omurzakova
Ilimkan Omurzakova

Reputation: 313

Scroll horizontally on mobile for only some containers and not for entire page

I need some cards to be scrolled horizontally, but the rest of the page scroll vertically for mobile devices (which will be implemented later into mobile app). When I use dev tools for mobile version everything seems to work. But when I'm opening on my phone everything scrolls horizontally and not just the container. Here is the example: https://codepen.io/Ilima/pen/EdYYZP How can I accomplish this?

*{
  margin: 0;
  padding: 0;
  -webkit-box-sizing: border-box;
          box-sizing: border-box;
}
.scroll {
  padding: 20px;
  height: 240px;
  width:calc(100% -5px);
  background-color: #fff;
  white-space: nowrap;
  overflow-y: hidden;
  overflow-x: scroll;
  -webkit-overflow-scrolling: touch;
}
.block {
  width: 200px;
  height: 200px;
  background: #ccc;
  display: inline-block;
  margin: 0 20px;
  box-shadow: 0px 3px 4px rgba(0, 0, 0, 0.2), 0 2px 6px rgba(0, 0, 0, 0.2);
  
}
.test {
  background: #EEEEEE;
  height: 1000px;
  overflow-x: hidden;
  width: 100%;
}
.test p {
  display: block;
  margin: 40px;
}
<div class="scroll">
  <div class="block"></div>
  <div class="block"></div>
  <div class="block"></div>
  <div class="block"></div>
  <div class="block"></div>
  <div class="block"></div>
  <div class="block"></div>
  <div class="block"></div>
  <div class="block"></div>
  <div class="block"></div>
  <div class="block"></div>
  <div class="block"></div>
  <div class="block"></div>
  <div class="block"></div>
  <div class="block"></div>
  <div class="block"></div>
</div>

<div class="test">
  <p style="overflow-y: auto;">This should not scroll horizontally on mobile</p>
</div>

Upvotes: 1

Views: 443

Answers (2)

matt
matt

Reputation: 2840

Or ... use a media query to just "undo" the scroll on larger screens.

overflow-x:hidden;

Upvotes: 0

brianespinosa
brianespinosa

Reputation: 2408

You're SO close. The width of the scroll container is impacting the overall width of the body on mobile. Because .scroll has a percentage width, that means it is relative to the parent width.

What you want to do is make sure the width of the html/body do not exceed the viewport width.

html,
body {
  width: 100vw;
}

Adding that will make sure the body does not exceed the width of the viewport and then the scrolling should work as you expect on mobile. You can also set width: 100vw; on the .scroll container and it will work as expected too. Since this is going to mobile you are probably better off setting html/body though.

Upvotes: 1

Related Questions