I have a three column layout that I want to be swipe-able in a mobile browser. I'm using scroll-snap to define three possible columns/positions for a horizontal scroll. This seems to be working fine.
However, I'd like to set the middle column to show up as the default, so that when the page is first rendered (on mobile), the middle column is shown and the user can either swipe right or left.
I am fine with either a CSS solution or a javascript solution which scrolls to the middle position. I've tried selecting various elements and using scrollTo or scrollIntoView, but I'm either missing something or it can't be done.
Here is a link to a codepen which contains a simplified version of the page in question: https://codepen.io/kvinklly/pen/OJEejWe
Below is the html and css from the codepen:
<div class="container">
<div class="item">
<div>1</div>
</div>
<div class="item">
<div>2</div>
</div>
<div class="item">
<div>3</div>
</div>
</div>
.container {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
border: 1px solid;
width: 320px;
height: 568px;
scroll-snap-type: x mandatory;
overflow-x: auto;
white-space: nowrap;
position: relative;
-webkit-overflow-scrolling: touch;
}
.item {
margin: 10px;
display: flex;
flex-direction: row;
scroll-behavior: smooth;
scroll-snap-align: center;
justify-content: center;
align-items: center;
&:first-child {
padding-left: 60px
}
&:last-child {
padding-right: 60px;
}
div {
display: flex;
width: 200px;
height: 300px;
border: 1px solid red;
border-radius: 15px;
justify-content: center;
align-items: center;
}
}
Well, chatGPT to the rescue. The answer is quite simple (I'll put it into my own revised code to fit the example). You can do it using JS like this: