CSS - fixed table headers

Check out my CodePen example here - Code

In this demo, I have a table inside a container where the table is larger than the container.

As you scroll horizontally, both the table and headers move accordingly.

However, when scrolling vertically, I want the headers to stick at the top while the content scrolls underneath. You can see a working version of this concept here - Code

The challenge I'm facing is maintaining the column widths and overall structure of the table when implementing sticky headers.

Do you have any suggestions on how I can achieve sticky headers without losing the width integrity of the table?

body{
  background: grey;
  font-family: sans-serif;
}
.page{
  background: white;
  width: 1200px;
  margin: 0 auto;
}
.table-con{
  overflow: scroll;
  max-width: 1200px;
  height: 500px;
} 

table{
  /*table-layout: fixed;*/
  border-collapse: collapse; 
  width: 1500px;
}

thead th:first-child{
  width: 20px;
  padding: 0;
}

thead th{
  text-align: left;
}

thead tr{
  border-bottom: 1px solid #444;
}

tbody td{
  border-bottom: 1px solid #aaa;
}

tbody tr:nth-child(even) td:not(:first-child){
  background: yellow;
}

tbody td:first-child{
  background: none;
  border: none;
  padding: 0;
}

th, td{
  padding: 10px 5px;

   &:first-of-type{
    padding-left: 20px;
  }

  &:last-of-type{
    padding-right: 20px;
  }
}

Answer №1

Hey there! Take a look at the code snippet below, it should provide some useful insight.

html, body{
  margin:0;
  padding:0;
  height:100%;
}
section {
  position: relative;
  border: 1px solid #000;
  padding-top: 37px;
  background: #500;
}
section.positioned {
  position: absolute;
  top:100px;
  left:100px;
  width:800px;
  box-shadow: 0 0 15px #333;
}
.container {
  overflow-y: auto;
  height: 200px;
}
table {
  border-spacing: 0;
  width:100%;
}
td + td {
  border-left:1px solid #eee;
}
td, th {
  border-bottom:1px solid #eee;
  background: #ddd;
  color: #000;
  padding: 10px 25px;
}
th {
  height: 0;
  line-height: 0;
  padding-top: 0;
  padding-bottom: 0;
  color: transparent;
  border: none;
  white-space: nowrap;
}
th div{
  position: absolute;
  background: transparent;
  color: #fff;
  padding: 9px 25px;
  top: 0;
  margin-left: -25px;
  line-height: normal;
  border-left: 1px solid #800;
}
th:first-child div{
  border: none;
}
<section class="">
  <div class="container">
    <table>
      <thead>
        <tr class="header">
          <th>
            Table attribute name
            <div>Table attribute name</div>
          </th>
          <th>
            Value
            <div>Value</div>
          </th>
          <th>
            Description
            <div>Description</div>
          </th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>align</td>
          <td>left, center, right</td>
          <td>Not supported in HTML5. Deprecated in HTML 4.01. Specifies the alignment of a table according to surrounding text</td>
        </tr>
        <tr>
          <td>bgcolor</td>
          <td>rgb(x,x,x), #xxxxxx, colorname</td>
          <td>Not supported in HTML5. Deprecated in HTML 4.01. Specifies the background color for a table</td>
        </tr>
        <tr>
          <td>border</td>
          <td>1,""</td>
          <td>Specifies whether the table cells should have borders or not</td>
        </tr>
        <tr>
          <td>cellpadding</td>
          <td>pixels</td>
          <td>Not supported in HTML5. Specifies the space between the cell wall and the cell content</td>
        </tr>
        <tr>
          <td>cellspacing</td>
          <td>pixels</td>
          <td>Not supported in HTML5. Specifies the space between cells</td>
        </tr>
        <tr>
          <td>frame</td>
          <td>void, above, below, hsides, lhs, rhs, vsides, box, border</td>
          <td>Not supported in HTML5. Specifies which parts of the outside borders that should be visible</td>
        </tr>
        <tr>
          <td>rules</td>
          <td>none, groups, rows, cols, all</td>
          <td>Not supported in HTML5. Specifies which parts of the inside borders that should be visible</td>
        </tr>
        <tr>
          <td>summary</td>
          <td>text</td>
          <td>Not supported in HTML5. Specifies a summary of the content of a table</td>
        </tr>
        <tr>
          <td>width</td>
          <td>pixels, %</td>
          <td>Not supported in HTML5. Specifies the width of a table</td>
        </tr>
      </tbody>
    </table>
  </div>
</section>

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

Dynamic div with height controlled by the content of the background image

I'm trying to figure out how to make a div with a background image of 100% width always maintain the aspect ratio of the image for its height. Is there a way to achieve this? In simpler terms, when I resize the page, I want the div to scale down whil ...

HTML email for resetting your password

When a user forgets their password, I would like to send them an email with a link to a page where they can reset it. What is the best way to structure this link? Should I include the username as a parameter in the URL, and if so, how can I ensure that t ...

Ensuring elements are correctly positioned

I am struggling to make the images in the following code align horizontally across the top and also need to align the h1's in the same way. I have tried using the vertical-align property, but it seems to behave oddly to me. HTML: <div class=&apos ...

Tips for creating floating and right-aligned notifications using CSS in Vue.js

Struggling to position my basic notification component in the top right corner. Here is my HTML: <div class="notifications"> <p>{{ notification.message }}</p> </div> This is my notifications class: .notifications { position: ...

Disappearing sticky-top navbar in Bootstrap when scrolling

I'm having trouble with the navbar on my website. Currently, it sticks to the top until I scroll out of the hero-image and then disappears. I would prefer the navbar to remain present throughout the entire page. Any suggestions on how to achieve this? ...

Toggle the submenu with a fade effect when jQuery is clicked

Currently, I am facing an issue with creating links that are supposed to open their respective submenus on click. However, the script I have written is opening all submenus instead of the specific ones assigned to each link. Sample HTML Code: <nav> ...

Adding alpha or opacity to the background image will give it a unique and

Is there a way to darken the background image while keeping the text color the same? Check out this code snippet on JSFiddle div { display:block; background:url('http://placehold.it/500x500') 0 0 no-repeat; background-color:rgba(0 ...

What are the steps for utilizing CSS Global Variables?

Hey there, thank you for taking the time to help me out. I'm having a simple doubt that I just can't seem to figure out. So... here's my '/pages/_app.js' file: import '../public/styles/global.css'; export default funct ...

Enhance the appearance of QTreeView items using a customized display delegate and CSS

In my QTreeView, I have a custom delegate set up for one of the columns to display a colored progress bar. The appearance of the progress bar depends on the content and I used the color information from option.palette to mimic the default delegate behavior ...

Ways to adjust the select element to match the width of its current option

As I work on building a form, I'm looking for a way to make the select element adjust its width based on the length of its current option. Essentially, I want the select element to expand or contract depending on the width of its longest option. I&ap ...

Is there a way to showcase English and CJK text vertically with CSS?

This particular issue was first discussed 14 years ago on Stack Overflow, but a definitive solution still remains elusive. My goal is to have both CJK and Latin characters displayed vertically, with their bottoms facing the right side. While writing-mode ...

Having trouble loading external CSS in HTML?

I have been attempting to load an external CSS file into my current HTML file without success. I have provided images showcasing the code: View the code here See the output here Currently, I am working on Windows and using Aptana Studio 3 as my IDE. ...

Does the zoom value in the HTML file adjust when I zoom in or out on the Google Map?

I'm uncertain if my question is sufficiently clear. Here's my dilemma: I've been utilizing the gmplot module in Python and I'm interested in adjusting the grids to be scalable based on the zoom level of the Google Map. However, being u ...

Inserting a line break in real-time within a JSX statement

Currently working on a React application that retrieves song lyrics from an API. The API provides me with a lyrics_body attribute as a string, which I use to showcase the lyrics on the webpage. However, when React renders it, the format is not ideal becau ...

Accordion menu with smooth CSS3 transitions

I created a unique accordion menu to replace the select form control, and I am interested in using CSS3 transitions to give it a smooth expand and contract effect. Feel free to check out my work on jsfiddle: http://jsfiddle.net/hKsCD/4/ In order to achi ...

Button Click Not Allowing Webpage Scroll

I am currently in the process of developing a website that aims to incorporate a significant amount of motion and interactivity. The concept I have devised involves a scenario where clicking on a button from the "main menu" will trigger a horizontal and ve ...

The performance of the animation on http://responsive-nav.com/ becomes erratic when viewed on Android devices

Recently, I came across a fantastic plugin that works perfectly on regular computer browsers. However, when I tested it on my android phone, the css3 animation for the dropdown appeared choppy and seemed to be dropping frames. Does anyone have suggestions ...

The dialog box is not taking up the full width of the browser window

I'm facing an issue with a dialog box that only occupies a portion of the browser width, despite having a width set to 100%. The backdrop, however, extends across the entire width. //App.js import React from "react"; import ConfirmationDial ...

arranging <li> elements in alphabetical order

I'm looking for a way to alphabetically sort an unordered list while still keeping the outer html intact. My current method sorts the list alphabetically, but it only reorganizes the inner html of the list elements and not the entire element itself. T ...

SVGs are not resizing correctly in Internet Explorer and there is unnecessary blank space around them

Recently, I made the decision to switch to using SVG symbols for one of my projects. However, I encountered a challenge as I needed these SVGs to be responsive. My main objective was to minimize the number of HTTP requests, leading me to explore the option ...