What is the technique for applying HTML element formatters to column headers using the to_html method to achieve rotation?

I am currently working with a Pandas DataFrame and I am looking for a way to display it on an HTML page with minimal empty space. Additionally, I am utilizing Bootstrap 4.

To format all elements of a column, I can use the to_html method along with table styles:

html = df.to_html(
    formatters={'COL_NAME': lambda x: '<b>' + x + '</b>'},
    classes='table table-striped df_data',
    escape=False
)

Furthermore, I can directly add HTML elements by replacing the values like so:

html = html.replace('<th>', '<th><div><span>')
html = html.replace('</th>', '</span></div></th>')
  • Is there a tidy method to incorporate these HTML elements into the headers?
  • I am following these steps to display rotated headers and optimize screen usage as shown in the image. I sourced the CSS styles from this page

    .df_data thead th {
        height: 140px;
        white-space: nowrap;
    }
    
    .df_data thead th > div {
        transform: translate(25px, 51px) rotate(315deg);
        width: 30px;
    }
    
    .df_data thead th > div > span {
        border-bottom: 1px solid #ccc;
        padding: 5px 10px;
    }
    

    However, the outcome is not as expected. The space is not optimized and the headers are misaligned. What adjustments should I make to maximize column space? I am willing to forego Bootstrap styles.

  • Is there a more direct approach to achieve this?

Any suggestions or recommendations would be greatly appreciated

Update 2019-26-02

The solution provided by @joshmoto seems promising, but I need to adjust column widths as I cannot predict the cell contents in advance (maximum of 10 characters).

Answer №1

For achieving the desired effect when the cell width varies, it is necessary to insert another div and position it with position: relative; within the table header cell. Subsequently, you can set the next child div to position: absolute; and adjust its position using left: 100%;, which will establish the right point of reference. Following this, you can implement the provided code from the codepen demo.

View the codeply working demo here

MAIN {
  padding-top: 30px;
  padding-bottom: 30px
}

.df_data {
  border-collapse: collapse
}

.df_data thead th {
  border-top: none;
  padding: 0
}

.df_data td {
  text-align: center;
  padding: 10px 5px;
  border: 1px solid #ccc
}

.df_data th.rotate {
  margin-left: 100%;
  height: 140px;
  white-space: nowrap
}

.df_data th.rotate>div {
  position: relative;
  width: 100%;
  height: 30px
}

.df_data th.rotate>div>div {
  position: absolute;
  left: 100%;
  width: 30px;
  transform: translate(-14px, -2px) rotate(315deg)
}

.df_data th.rotate>div>div>span {
  border-bottom: 1px solid #ccc;
  padding: 5px 10px
}

.df_data th.row-header {
  padding: 0 10px;
  border-bottom: 1px solid #ccc
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" />
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>

<main role="main" class="container">
  <table class="table table-striped df_data">
    <thead>
      <tr>
        <th></th>
        <th class="rotate">
          <div>
            <div><span>Column header 1</span></div>
          </div>
        </th>
        <th class="rotate">
          <div>
            <div><span>Column header 2</span></div>
          </div>
        </th>
        <th class="rotate">
          <div>
            <div><span>Column header 3</span></div>
          </div>
        </th>
        <th class="rotate">
          <div>
            <div><span>Column header 4</span></div>
          </div>
        </th>
        <th class="rotate">
          <div>
            <div><span>Column header 5</span></div>
          </div>
        </th>
        <th class="rotate">
          <div>
            <div><span>Column header 6</span></div>
          </div>
        </th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <th class="row-header">Row header 1</th>
        <td>2w98</td>
        <td>3423423</td>
        <td>35325233542947742747344</td>
        <td>12213&gt;</td>
        <td>453842589389582</td>
        <td>49849</td>
      </tr>
    </tbody>
  </table>
</main>

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

What is the process for moving a tap-target button with materialize css?

Looking for tips on how to relocate a tap-target button that's currently stuck in the bottom right corner of the screen. I've experimented with various methods like adjusting margins, padding, and even nesting it in an outer div, but nothing seem ...

The labels assigned to buttons will direct users to unique links specifically designated for that button

I've been working on a website to share some code I created, but my skills in HTML and CSS are not the best. Please forgive me if there are obvious mistakes. Here's the code I have so far: <!DOCTYPE html> <html> <head> ...

Modal box fails to refresh content

Currently, I am in the process of learning how to modify my blog using a modal window. However, when I click on the edit button within the modal, an error message 'Failed to execute 'fetch' on 'Window': Invalid name' appears i ...

Move a div to line up with a table row when clicked using jQuery

As I mentioned in a previous post, my experience with jQuery is limited and I apologize for that. The task I am attempting to accomplish seems relatively straightforward. Here's an overview of the situation: I have a table enclosed within a div. Each ...

plotting two data frames on a single graph

I am working with two data frames which are: Country,Factory,worker_efficiency USA,factory_A,90 Germany,factory_A,93 France,factory_A,90 USA,factory_B,80 Germany,factory_B,94 France,factory_B,91 USA,factory_C,78 Germany,factory_C,95 France,factory_C,92 US ...

The absence of the iframe in ie8 is causing problems that cannot be fixed with relative positioning

On a website, I am integrating an external 2-factor authentication solution called Duo Web using their PHP and Javascript. It works smoothly on all browsers except for IE8. When the user passes the initial login screen, the 2FA login page loads, but the if ...

JQuery .click Event doesn't center elements even with transform-origin adjustment

In the JSfiddle provided below, you can see that after a click event occurs, two span (block) elements rotate 45deg to form an "X". However, both elements are slightly shifted left, creating an off-center "X" relative to the parent's true center-origi ...

I must modify the initial statement to appear in bold from the paragraph with the use of JavaScript and CSS

Mr. XYZ and Mrs. ABC are known for their integrity. They own a stylish car. In the next paragraph, I would like to emphasize the first sentence by making it bold, We admire our exceptional leader J.K.L. He shows great potential. In this section, I wan ...

Horizontal Alignment of DIV Tags

I'm currently working on aligning some div tags to serve as contact links on my website. My goal is for them to be positioned on the right-hand side and aligned in a single line. Here's how they look at the moment: https://i.sstatic.net/rQ1uG.p ...

python asyncio.gather incorporates user input into the final result

My function looks something like this: async def funcn(input: input_type) -> output_type: .... return output I am using asyncio.gather to call it in the following way: output = await asyncio.gather(*[funcn(input) for input in input_list]) The retu ...

Is there a way to confirm if all div elements have a designated background color?

I have a scenario where I have dynamically added several divs with a specific class to my webpage. These divs change color when the user hovers over them. I am trying to trigger a specific function once the last div has been set to a particular backgroun ...

Proceed with the program's execution using the predetermined value if no input is provided

I am currently working on a selenium script that automates the process of filling in credentials on various websites. To make this more efficient, I have set up a dictionary with different profiles and their corresponding login details. This way, users can ...

Iterating through the columns in a DataFrame

I am working with a dataframe and I need to implement baseline correction. The code snippet below showcases what I have attempted for one column, but my goal is to apply it to every column in the dataframe using a loop. How can I achieve this? df=pd.read_c ...

I'm struggling to understand how to interpret this. The v-tab function seems to be generating a button with various properties, but I'm unsure which specific property is related to

The V-tab below generates the button known as the right one on the v-app-bar: https://i.stack.imgur.com/DzNmq.png <v-tab :to="'/demo'" active-class="text--primary" class=&quo ...

`Unable to find the button using Selenium and perform a click action on it`

I've attempted various methods to automate clicking the checkout button using WebDriverWait, XPath, and Class, but unfortunately, it's not working as expected: HTML <div class="confirm-container row"> :before <div clas ...

The grid images transition at set intervals using jQuery or another JavaScript framework

I am facing a challenge with developing an image grid that transitions some images at random intervals using either jQuery or another method in JavaScript. It's important to note that I don't want all the images to change simultaneously; each gro ...

Guide for creating a scroll-triggered rotation animation using only JavaScript

Looking to achieve a cool scroll effect with an image that rotates on the X-axis by a specific degree, such as 70deg. The goal is to have the image's rotateX value change to 0deg when it enters the viewport upon scrolling and revert back to 70deg whe ...

"Placing the save button on top of a div - a step

I am trying to position a div with an ID below a save button in my HTML code. The current setup looks like this: <button id="item_new" data-action="create" class="floating-button mdl-button mdl-js-button mdl-button--fab mdl-js-ripple-effect mdl-button- ...

CSS Styled Product Index

Currently, I am working on creating a product catalog using React and CSS. Everything is going smoothly except for the last row of products. The issue with the last row is that it only contains 1 element, and due to the flex-grow: 1 setting, it ends up ta ...

Tips on introducing a random pattern into a Javascript gaming experience

To kick off the game, let's generate a pattern randomly. Follow these steps: -Include a function that generates the pattern. (Hint: JavaScript's Math.random function might come in handy) -Invoke your new function from the startGame function I&a ...