The issue of a non-functional grid with scroll in a flexbox

I've encountered a problem while working with the grid layout using divs and flexbox. The header, which I want to be fixed, is overlapping with the first row and I'm struggling to get the scrolling behavior right. How can I address this issue? I thought about applying overflow-y: scroll only to the grid body, but that introduces an extra horizontal scrollbar.

var data = [{
                "title": "Chicken Tortilla Soup!",
                "youTubeId": "B7JUzPTib9A",
                "rating": 0.9708955223880597,
                ...
            }];

            loadData();

            function loadData() {
                $(".gridBody").empty();
                $.each(data, function(index, item) {
                    let row = $("<div>", {
                        class: "gridRow"
                    });
                    $.each(item, function(key, value) {
                        let cell = $("<div>", {
                            class: "gridCell",
                            text: value
                        });
                        $(row).append(cell);
                    });
                    $(".gridBody").append(row);
                });
            }
            

                html,
                body {
                    height: 100%;
                }

                #main {
                    height: 100%;
                    width: 80%;
                    margin: 0 auto;
                }

                .grid {
                    background-color: #fff;
                    display: flex;
                    flex-direction: column;
                    overflow-x: auto;
                    height: 80%;
                }

                .gridHeader {
                    height: 100px;
                }

                .gridBody {
                    overflow-y: scroll;
                }

                .gridHeader,
                .gridRow {
                    display: flex;
                }

                .gridHeader .gridCell {
                    font-weight: bold;
                }

                .gridCell {
                    border: 1px solid #000;
                    min-width: calc(100% / 6);
                    padding: 10px;
                    word-break: break-word;
                    text-align: center;
                }
            
Title
youtubeid
Rating
Views
Thumbnail
Length

Answer №1

By default, a flex container has the property flex-shrink: 1, allowing flex items to shrink to fit the container. This might be causing your header to appear shorter than the specified height: 100px, resulting in overlapping rows.

To resolve this issue, you can override the default setting with these solutions:

.gridHeader {
   height: 100px;
   flex-shrink: 0;
}

Alternatively, you can use:

.gridHeader {
   flex: 0 0 100px;
}

(For a detailed explanation, refer to Differences between flex-basis and width)

Furthermore, the presence of a vertical scrollbar in the grid body can disrupt column alignment with the fixed header. To address this, consider the following fix:

  • Fix for alignment issue in HTML table

var data = [
  {
      "title": "Chicken Tortilla Soup!",
      "youTubeId": "B7JUzPTib9A",
      "rating": 0.9708955223880597,
      "views": 73693,
      "thumbnail": "https://i.ytimg.com/vi/B7JUzPTib9A/mqdefault.jpg",
      "length": 265
    },
    ...
    (Additional data entries)
    ...
];

loadData();

function loadData() {
  $(".gridBody").empty();
  $.each(data, function(index, item) {
    let row = $("<div>", { class: "gridRow" });
    $.each(item, function(key, value) {
      let cell = $("<div>", { class: "gridCell", text: value });
      $(row).append(cell);
    });
    $(".gridBody").append(row);
  });
}
html, body {
  height: 100%;
}

#main {
  height: 100%;
  width: 80%;
  margin: 0 auto;
}

.grid {
  background-color: #fff; 
  display: flex;
  flex-direction: column;
  overflow-x: auto;
  height: 80%;
}

.gridHeader {
  flex: 0 0 100px;   /* new */
}

.gridBody {
  overflow-y: scroll;
}

.gridHeader, 
.gridRow {
  display: flex;
}

.gridHeader .gridCell {
  font-weight: bold;
}

.gridCell {
  border: 1px solid #000;
  min-width: calc(100% / 6);
  padding: 10px;
  word-break: break-word;
  text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">
  <div class="grid">
    <div class="gridHeader">
      <div class="gridCell">Title</div>
      <div class="gridCell">youtubeid</div>
      <div class="gridCell">Rating</div>
      <div class="gridCell">Views</div>
      <div class="gridCell">Thumbnail</div>
      <div class="gridCell">Length</div>
    </div>
    <div class="gridBody">
    </div>
  </div>
</div>

Answer №2

Make sure to include box-sizing: border-box; in the style for .gridCell. Additionally, consider changing overflow-y: scroll to overflow-y: overlay;. Also, adjust height: 100px; to min-height: 100px; for the header.

var data = [
  {
      "title": "Chicken Tortilla Soup!",
      "youTubeId": "B7JUzPTib9A",
      "rating": 0.9708955223880597,
      "views": 73693,
      "thumbnail": "https://i.ytimg.com/vi/B7JUzPTib9A/mqdefault.jpg",
      "length": 265
    },
    // Remaining data content...
];

loadData();

function loadData() {
  $(".gridBody").empty();
  $.each(data, function(index, item) {
    let row = $("<div>", { class: "gridRow" });
    $.each(item, function(key, value) {
      let cell = $("<div>", { class: "gridCell", text: value });
      $(row).append(cell);
    });
    $(".gridBody").append(row);
  });
}
html, body {
  height: 100%;
}

#main {
  height: 100%;
  width: 80%;
  margin: 0 auto;
}

.grid {
  background-color: #fff; 
  display: flex;
  flex-direction: column;
  overflow-x: auto;
  height: 80%;
}

.gridHeader {
  min-height: 100px;
}

.gridBody {
  overflow-y: scroll;
}

.gridHeader, 
.gridRow {
  display: flex;
}

.gridHeader .gridCell {
  font-weight: bold;
}

.gridCell {
  border: 1px solid #000;
  min-width: calc(100% / 6);
  padding: 10px;
  word-break: break-word;
  text-align: center;
  box-sizing: border-box;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">
  <div class="grid">
    <div class="gridHeader">
      <div class="gridCell">Title</div>
      <div class="gridCell">youtubeid</div>
      <div class="gridCell">Rating</div>
      <div class="gridCell">Views</div>
      <div class="gridCell">Thumbnail</div>
      <div class="gridCell">Length</div>
    </div>
    <div class="gridBody">
    </div>
  </div>
</div>

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

When a decimal of 0.02 is added to a number in javascript, it may lead to

I am attempting to create an array of numbers ranging from a specific minimum value to a certain maximum value with a specified decimal interval, such as 0.02. For instance, the sequence would be like: 1.00, 1.02, 1.04, 1.06 The issue arises when the code ...

Creating a realistic typewriter effect by incorporating Code Block as the input

I am looking to add a special touch to my website by showcasing a code segment with the Typewriter effect. I want this code block not only displayed but also "typed" out when the page loads. Unfortunately, I have been unable to find a suitable solution s ...

Designing stylesheets for larger screens to optimize the layout

I am currently working on the front-end design of a website and could use some assistance regarding element sizing. While the layout and elements look great on my 19-inch, 1440x900 resolution monitor, I noticed that everything appears tiny when viewed on a ...

Decomposing LocalStorage data in React using JavaScript

How can I retrieve this element from localStorage? https://i.sstatic.net/e8K3u.png Although I am able to console.log(product.priceHistory), how do I access its price element? useEffect(() => { let productFromLocalStorage = localStorage.getItem(id ...

Failed to load Gulpfile.js in the Task Runner Explorer of Visual Studio 2019 version 16.6.2

Displayed below is the result in the output error window. Failed to execute "D:\TortSVN\Oil Diversity\Main Web App\LatsetOildiversity\Gulpfile.js"... cmd.exe /c gulp --tasks-simple fs.js:27 const { Math, Object } = primordials; ...

External API data is shown in the browser console but appears as undefined on the page

Can you please lend me a helping hand? I am facing a critical issue while attempting to retrieve data from an external API using axios in NextJS (Reactjs)/TypeScript through getServerSideProps. The data fetching is successful, and the JSON is returned on t ...

Tips for adjusting the minimum attribute within an input field with jQuery

In my form, I have an input field with arrows (up and down). Next to it, there are two buttons: + and -. When I click on the input field and then use the arrow, the system retrieves the value from a dropdown list, which works fine. However, when I use the ...

I encountered an issue with rendering static images when attempting to package my node-express app with pkg

Struggling to display an image from the public folder in my express app? I could use some guidance on configuring the path to properly render images or css files within the public folder when creating an executable file using pkg. Here's a snippet of ...

Tips for submitting an Ajax Form with identical Name attributes?

One part of my form consists of input fields with the same 'Name' values that will be stored as an Array. I am attempting to send these values via AJAX to PHP for updating my database. The challenge I'm facing is figuring out how to send t ...

Manipulating arrays within Vuejs does not trigger a re-render of table rows

I have successfully generated a user table using data retrieved from an ajax request. The table has a structure similar to this: [Image of Table][1] Now, when an admin makes changes to a user's username, I want the respective row to update with the n ...

What is the process for uploading or hosting a Reactjs website?

Currently, I am in the process of developing a React web application project using create-react-app. The project is nearly complete and as part of my preparation, I have been researching how to obtain a hostname. During my research, I came across https://w ...

There seems to be an issue with the HighCharts chart export feature as it is not showing the Navigator graph

We are currently using HighCharts version 4.2.2 http://api.highcharts.com/highcharts/exporting While going through their exporting documentation, I made a decision to not utilize their default menu dropdown. Instead, I only needed access to the .exportCh ...

What could be causing the template UI to not display the Vue data?

As someone new to Vue, I have defined my Vue code in the following way: import Vue from "vue"; export default Vue.extend({ data: () => { message: "show message"; }, }); <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js ...

"Implementing a function where two different elements can change the text of a button

I have created a custom FAQ script using dl, dt, and dd elements: $('.faqs dd').hide(); // Hide all DDs inside the .faqs container $('.faqs dt').hover(function(){ $(this).addClass('hover' , 'slow')},function(){ ...

What is the method for extracting an entire space-separated string into a PHP variable from HTML options?

When the select tag fetches options from a MySQL database and assigns a value to a PHP variable for echoing, only the first part of the text is displayed. For example : Option: Vijay Sharma Echo Output: Vijay <select name="facultyname" oncha ...

Finding the row index in an Angular material table

How can I retrieve the row index in an Angular material table? <td mat-cell *matCellDef="let row"> <mat-checkbox (click)="$event.stopPropagation()&quo ...

The issue with Angular 4 imports not refreshing in a .less file persists

Currently, I am in the process of developing a small Angular project that utilizes less for styling purposes. My intention is to separate the styling into distinct folders apart from the components and instead have a main import file - main.less. This fil ...

Animation of active chat list items on Whatsapp

Has anyone figured out a simple method to create an animation like the one in Whatsapp? For example, when you are on a chat screen and go back to the chat list, have you noticed how an active element is briefly highlighted in gray (to indicate which chat ...

Once an email address is entered, kindly instruct the driver to press the tab key twice for navigation

Adding a user to a website involves entering an email address first, which is then checked against the server's list of users. However, the issue arises when the email validation doesn't occur until clicking outside the input box or pressing tab ...

What could be the reason behind the malfunctioning of my three.js lighting system?

I am struggling to identify the issue with this code snippet (http://jsfiddle.net/resistdesign/s6npL/). Despite referencing the documentation and some examples, the lights don't seem to be functioning as expected. var camera, scene, renderer, geometr ...