Ensure the central alignment of the focused item within the horizontal scroll

I have successfully implemented a horizontal scroll container using <HTML/> and CSS:

body {
background-color: #212121;
}

.scroll_container {
height: 100px;
width: 400px;
display: flex;
align-items: center;
overflow-y: hidden;
width: 100%;
height: 20%;
}

.scroll_container_sub {
height: 100px;
min-width: 230px;
float: none;
display: inline-block;
zoom: 1;
margin: 10px;
border: solid 1px transparent;
border-radius: 15px;
background-color: #fff;
}
<div class="scroll_container">
        <div class="scroll_container_sub"></div>
        <div class="scroll_container_sub"></div>
        <div class="scroll_container_sub"></div>
</div>

What I am attempting to accomplish:
Is it feasible to automatically center one item (scroll_container_sub) within the scroll_container every time? This would be especially beneficial for mobile users.
EXAMPLE:
After scrolling, the middle item should be centered horizontally:
https://i.sstatic.net/F14C8.png
(image: mobile view)
This means situations like the following should not occur:
https://i.sstatic.net/E8FTm.png
Because none of the containers are centered. Ideally, when looking at a scroll position like this, the scroll view would automatically center one of the containers.
For a more detailed explanation: :)
In the following link, you can see what I am trying to achieve. Pay attention to the first few seconds.
The cards are consistently centered after the user swipes. This is exactly what I am striving for:
https://www.youtube.com/watch?v=UsXv6VRqZKs Do you need a live example? No Problem. You can find them in the Google Play Store. For instance, consider this swiper:
https://i.sstatic.net/5CyUA.jpg

~filip

Answer №1

2022 update: In the current landscape, consider using scroll-margin unless compatibility with older browsers is a concern.

Here is the implementation and concept behind the JavaScript logic:


The basic principle is as follows - locate the desired element, determine its midpoint (x + width / 2), and then subtract half of the container's width from that value:

window.addEventListener("load", function(e) {
  var container = document.querySelector(".scroll_container");
  var middle = container.children[Math.floor((container.children.length - 1) / 2)];
  container.scrollLeft = middle.offsetLeft +
    middle.offsetWidth / 2 - container.offsetWidth / 2;
});
body {
background-color: #212121;
}

.scroll_container {
    height: 100px;
    width: 400px;
    display: flex;
    align-items: center;
    overflow-y: hidden;
    position: relative;
    width: 100%;
    height: 20%;
}

.scroll_container_sub {
    height: 100px;
    min-width: 230px;
    float: none;
    display: inline-block;
    zoom: 1;
    margin: 10px;
    border: solid 1px transparent;
    border-radius: 15px;
    background-color: #fff;
}
<div class="scroll_container">
        <div class="scroll_container_sub"></div>
        <div class="scroll_container_sub"></div>
        <div class="scroll_container_sub"></div>
</div>

If you wish to dynamically apply this functionality, it's advisable to wait for the scrolling action to finish, calculate the new scrolling position, and smoothly transition towards it over a specific period.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transitioning images in JQuery by using a rollover effect

Is there a way to use Jquery for a hover effect that transitions images with a slide up animation? I've looked everywhere online, but I can't seem to find a code that works. All the examples I've found use fadeIn or fadeOut. Thank you for yo ...

Automatic padding within Bootstrap5

I'm struggling to understand why I am experiencing a consistent padding at the bottom of my container in Bootstrap5. I attempted to use align-items-center within the row to center the content, but it had no effect. <!DOCTYPE html> <html la ...

Tips for maintaining the navigation tab's consistent appearance

Whenever I click a button on the sidebar and the current tab is the second tab, the navigation bar switches to display the first tab. How can I prevent this switch and keep the second tab displayed when clicking a button on the sidebar? The code for this ...

Issues encountered while utilizing Bliss as the template engine in NodeJS/Express

Seeking assistance in transitioning from Jade to Bliss as the template engine for a basic Express web application on NodeJS. Here is the code snippet from app.js: var express = require('express'), routes = require('./routes'), ...

Creating visuals from written content

I am attempting to transform Y[0] into an image rather than text. Currently, it is only displayed as a plain text link and not as an image. <html> <head> <script type="text/javascript"> function modifyContent(){ var rows=document.g ...

What is the best way to increase the value of a variable using jQuery?

As I work on adding dates to a slider, I find myself needing to increment the values with each click. Initially, I start with the year - 2. $('#adddates').click(function() { var year = 2; $("#slider").dateRangeSlider({ bounds: { ...

How can I extract a specific portion of HTML content using C#?

I am working on a page where I need to extract a substring using the following code: static string GetBetween(string message, string start, string end) { int startIndex = message.IndexOf(start) + start.Length; int stopIndex ...

What causes the html5 <audio> tag to appear differently on Chrome versus IE browsers?

When viewed in Chrome, the design appears clean and compact, but when seen in Internet Explorer, it looks large and overwhelming. Check out the screenshots below.. Do you have any suggestions to fix this issue? Know of any mp3 hosting platforms with an emb ...

Ways of extracting specific information from a JSON file with the help of jQuery

I am currently attempting to parse a JSON file that is stored locally on my system using jQuery. I am specifically interested in retrieving certain data from the file, which is structured like this: {"statements":[{"subject":{"uriString":"A","localNameIdx ...

jQuery: Managing and modifying values for dynamically generated input elements

Hello, I am currently working with the latest version of jQuery and have a table set up where clicking on the "Add" button appends a row of inputs. My goal is to calculate the total price for each particular product based on keyup events (i.e., qty * price ...

Bespoke search functionality using AJAX and tags in WordPress

I have created a custom search form in my WordPress theme that looks like this: <form role="search" class="form" method="get" action="<?php echo home_url('/');?>"> <input type="search" id="keyword" class="inp-search" onclick="sh ...

What is the best way to make a div expand to the full width of the screen while still being contained within its parent div?

I am facing an issue with the black bar at the bottom of the slider not stretching full-width on the screen. While it works fine on the left, the right side is cut off at the container edge. I am using Master Slider if that's relevant information. Can ...

Retrieving AJAX data in a Node.js environment

In my HTML application, I am utilizing AJAX to showcase the output on the same page after the submit button is clicked. Before submitting, I am able to retrieve the values passed in the HTML form using: app.use(express.bodyParser()); var reqBody = r ...

Save and retrieve documents within an electron application

Currently, I am developing an application that will need to download image files (jpg/png) from the web via API during its initial run. These files will then be stored locally so that users can access them without requiring an internet connection in the fu ...

Deleting JSON files using Discord and Node.js by requiring them from a specific folder

Currently, I am in the process of developing a Discord bot using Node.js. One of the functions within the bot utilizes JSON files to store information about specific entities. I aim to create a command in Discord that, when called with a specific name asso ...

Submitting late leads to several consecutive submissions

I am working on a jQuery code that aims to introduce a short time delay to allow for the proper execution of an AJAX request: $('#form_id').submit(function(e) { e.preventDefault(); $submit_url = $(this).data('submitUrl'); ...

"Using jQuery to add emphasis to a table row and remove it again

I have a table with multiple rows, where I have styled each odd row in one shade of gray and the even rows in slightly different shades to make it easier to read. When clicking on a row, I am currently highlighting it with a different color to indicate wh ...

Textfield with autocomplete dropdown

I have a text field on my website that needs to work as an autocomplete box. I have included the following code in the "headerbar" section of my page: Find :<input type="text" class="input2" style="margin-bottom:0px;" id="customersearchfield"> < ...

Adjusting the spacing between characters in SVG text elements

Take a look at this unique SVG: <svg xmlns="http://www.w3.org/2000/svg"> <defs> <style type="text/css"><![CDATA[ .code { font-family: monospace; white-space: pre; tab-size: 4; } ]]></style> </defs> <text class="cod ...

Add a trash can or delete icon within every row of a table using Vue.js

I am new to vue.js and I'm struggling to implement a trash icon in each row of a table for deleting rows. Additionally, I'm trying to make the input of a cell act as a dropdown menu or list within the table rows. I recently came across this scrip ...