What is the most effective way to prevent a <pre> element from overflowing and instead horizontally scrolling when placed within a table cell that is not

I am faced with the following situation:

<table>
    <tbody>
        <tr>
            <td>
                <pre style="overflow: scroll;">
                    (very long lines of text)

Find my JSFiddle here: https://jsfiddle.net/x7n8w02f/

In this specific context, I have taken into account these points:

  • The <table> cannot be set to table-layout: fixed (on the actual webpage it has a width: 100% while in the JSFiddle it's width: 600px).
  • The width of the <td> varies.
  • No wrapping should occur within the <pre> tag and whitespace must be maintained.
  • The content inside the <pre> should occupy the full width of the <td>.
  • If the content within the <pre> exceeds the width of the <td>, it should horizontally scroll within the bounds of the <td>.

Despite my efforts, I haven't found a viable solution for this!

All the solutions I've come across so far impose certain restrictions on the document and stylesheet:

  • Using table-layout: fixed on the <table>.
  • Assigning an absolute width to the <pre> with overflow: scroll (or overflow-x: scroll), for example, width: 500px as opposed to width: 100% (which doesn't function as intended).
  • I have experimented with different combinations of CSS properties such as white-space, word-wrap, overflow, and overflow-x without success.

Answer №1

To meet the requirements correctly, it seems advisable to place the pre element within an absolutely positioned box inside a relatively positioned td element. Here is an example of how this can be achieved.

table {
  border: 1px outset #999;
  
  width: 600px;
}
td, th {
  border: 1px inset #999;
}
.pre-container {
  position: relative;
}

pre {
  border: 1px solid red;
  overflow: auto;
  position:absolute;
  left:0;
  right:0;
  margin:0;
  top:0;
  bottom:0;
}
<table>
<tbody>
  <tr>
    <td>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</td>
    <td class="pre-container">
      <pre>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec nisl nisi, volutpat eget tempus vitae, iaculis non magna. Phasellus efficitur ante ipsum, eget posuere diam dapibus at. Sed vel leo sit amet sapien feugiat congue. Nunc lorem velit, bibendum eu dignissim eu, efficitur ultrices metus. Suspendisse accumsan dolor ut tortor maximus, et volutpat velit eleifend. Donec commodo malesuada auctor. Proin cursus euismod porttitor. Duis posuere id ex sollicitudin vestibulum. Sed nisi odio, imperdiet ac mollis sit amet, luctus id odio. Fusce laoreet libero non nunc ornare, ac pharetra mi rutrum. Quisque rhoncus vehicula lorem, sit amet consequat neque. Nullam sodales ligula ac orci tincidunt semper. In efficitur magna ut viverra eleifend.

Donec luctus purus nunc, id suscipit nisi dignissim quis. Vivamus vel ligula massa. Proin nec scelerisque ligula. Mauris tristique metus enim. Quisque blandit nunc at nunc maximus laoreet. Nunc nisl sapien, lacinia vitae risus vitae, rutrum interdum nibh. Nunc a sem sem. Ut leo lectus, tempus a sagittis eu, mattis eu orci. Pellentesque dignissim mi diam, et sollicitudin leo facilisis pretium. Ut et tempor dolor. Suspendisse laoreet odio elit, at ultricies justo pellentesque quis. Vestibulum et diam ac ipsum laoreet maximus ac eu elit. Integer et elementum urna.

Curabitur sagittis tortor eu justo laoreet, nec pharetra massa congue. Duis hendrerit venenatis diam, non suscipit arcu. Quisque aliquam pretium mauris, ac cursus risus eleifend nec. Nulla non sem ac mi auctor tempus in nec velit. In cursus vel ex nec pellentesque. Etiam consequat eget libero nec dictum. Vestibulum viverra neque vel urna semper vehicula. Praesent ac felis sollicitudin, convallis nisi vel, consequat lorem. Morbi eu elit at enim tempor maximus vel ut magna. Integer dignissim convallis consequat.

Fusce aliquam libero in sem volutpat rhoncus. Suspendisse vulputate interdum nibh non efficitur. Morbi massa dolor, egestas a sodales a, rhoncus quis turpis. Vivamus velit erat, rutrum vitae lectus sed, luctus vulputate augue. Aenean elementum tortor eros, eget hendrerit purus viverra eget. Praesent ultricies pulvinar gravida. Nullam pulvinar feugiat laoreet. Fusce sit amet est facilisis, mattis erat a, consectetur felis. Sed eleifend faucibus felis, eget auctor nunc egestas suscipit. Sed in lobortis mi. Phasellus aliquet elit at tristique ullamcorper. Nullam augue eros, ornare et nisl ac, tempor volutpat sem. Praesent in felis vehicula, imperdiet mi eget, laoreet diam.

Praesent at tellus diam. Fusce vulputate, ipsum non vulputate vehicula, elit sem viverra mi, eu suscipit arcu leo et mi. Curabitur nec dolor ultrices, bibendum eros hendrerit, gravida ex. Donec ac porttitor erat. Nullam gravida egestas mi, vel tristique ante suscipit nec. Nullam ut ante rhoncus nisi varius feugiat. Pellentesque aliquet tincidunt ante vitae sollicitudin.</pre>
    </td>
  </tr>
  <tr>
    <td>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</td>
    <td>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</td>
  </tr>
</tbody>
</table>

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

I am looking to position the search bar all the way to the right side

I've been struggling to properly align the search bar within my navigation bar. Despite my best efforts, I can't seem to get it right. Below is just a snippet of my navbar code, showcasing the search bar within a div container. .search { ...

Placing the error message for validation in its appropriate position

My login form has a layout that looks like this: https://i.stack.imgur.com/i7rCj.png If I enter incorrect information, it displays like this: https://i.stack.imgur.com/ItNJn.png The issue is that when the error message appears, it causes the login form ...

Showcasing Information Using AngularJS from a Json Array

My goal is to present data from a JSON array in a table using the code below. However, all the data is currently being shown in one row instead of each record appearing on separate rows with alternating colors - grey for even rows and white for odd rows. I ...

Property float does not account for margin values

Currently delving into the world of the semantic-ui framework, I have been working with segments. Here is a snippet of my code: <!DOCTYPE html> <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery ...

Storing a stylesheet on the identical server as the application through the Rails Asset Pipeline

Currently, I am utilizing a JavaScript library that necessitates a stylesheet to be located on the same domain as the application. My assets are being hosted on S3 via the Rails Asset Pipeline, and I would prefer to maintain this setup. I only require one ...

Two elements occupy the rest of the vertical space

In the center, there is a div with content inside. I want the top and bottom divs to occupy the remaining space. Similar to this example <div class="container"> <div class="top"> </div> <div class="middle"> C ...

Numerous elements positioned absolutely are overlapping

I am working on a website with a unique slide layout design. I am currently focusing on two specific slides: https://i.stack.imgur.com/xngF4.png and https://i.stack.imgur.com/W19tJ.png My goal is to include a button on each individual slide, similar to th ...

Managing the height of a TextArea within a Flexbox environment

After exploring various methods for achieving auto-height in a textarea, I decided to go with the contenteditable approach as it seemed cleaner to me. However, while it worked perfectly on its own, it failed when placed within flexbox containers. I experi ...

What is the solution to prevent background-attachment:fixed; from distorting the image?

Looking to create a scrolling background image that doesn't stretch? Typically, using background-attachment: fixed; works, but it's causing the image to stretch and lose positioning capabilities. If you want to see the issue in action, check out ...

Glitch in CSS causing issues with drop-down menu

When hovering over the Gallery, the sub menu list displays next to each other, but I want Sub 1 and Sub 2 to display below each other as a dropdown. How can I improve this code and is there any unnecessary code in it? Here is the picture: HTML: <div ...

Generate a purposely filled css grid with excessive content

I am attempting to design a horizontal scrolling widget that resembles an image carousel but with text and icons. This widget will contain multiple columns, but only one will be visible at a time while the others will have 'overflow: hidden'. T ...

"Enhancing iPhone User Experience with CSS Hover Effects

I am experiencing an issue with my website where the hover functionality works perfectly on all devices except for iPhones. On an iPhone, users have to continuously press the screen until the hover transition completes in order to view the information. I ...

The hover functionality fails to activate when a z-index is applied

My issue revolves around 2 divs: one containing a link and the other a box-shaped container. The link is set with position:fixed; causing it to fly over the container div. To resolve this, I attempted to assign a negative z-index value to the link, but unf ...

Displaying elements side by side on larger screens and centered on smaller screens

Is there a way to arrange elements next to each other on wider screens, aligning them left and right, while also centering one above the other on narrower screens? Preferably without using media queries: ...

JavaScript takes the spotlight before CSS

Currently experiencing this issue in Chrome, although Firefox seems to be working fine so far. Here is a greatly simplified version of the problem: HTML: <div class="thumbnail"> <a href='#' id="clickMe">Click me!</a> </d ...

Print the page number using HTML and PHP

Is there a way to center page numbers in HTML? I have the code below that echoes the numbers, but they always appear on the left side of the page. I tried wrapping them in a div to center them, which worked, but then each number is enclosed in its own d ...

Creating a unique design by displaying text in a modern, diagonally split rectangle using HTML and CSS

To creatively display the diagonal of a fictional rectangle using HTML/CSS, along with text written both above and below it. The main objective is to create a heading for a unique table design in the top left corner. This will help describe the row header ...

Utilizing z-index and position in CSS for a clean separation between design and functionality!

I have been experimenting with the yui-grids css framework, utilizing three columns. I am placing all the decorative design elements in the left column and centering them using z-index and relative positioning. In the center column, I am focusing on more ...

The page width seems incredibly wide right now, and I'm having trouble pinpointing which CSS element is responsible for this

My website is on Wordpress and the page widths seem to be too wide. I have tried looking for the culprit in the code, but so far no luck... ...

Utilizing static HTML, CSS, and JavaScript for secure backend administrative control

Seeking a solution for my static html, CSS, and JS website which includes some Jquery elements. I want to implement a user-friendly backend system that allows non-developer admins to log in, easily edit sections or change images with their own preferences. ...