Set the CSS table to have a width of 100% and ensure that the table data cells have hidden

My table has a 100% width, and some of the td elements have overflow hidden. I want to make their text appear as ellipsis when it's too long.

I can achieve this with fixed td sizes, but I need them to be relative to the content.

This question was first posted 3 years ago on Stack Overflow: CSS: 100% width table, with cells that have hidden overflow and irregular/minimal cell widths

There haven't been any responses yet, so I'm wondering if it's possible now.

Here is an example on jsFiddle: https://jsfiddle.net/gd1fogee/

Below is a snippet:

table{
  width:100%;
}
td{
/*max-width: 150px !important; */
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
      padding: 3px 5px;
}
<div style="width:400px;display:block;">
<table>
  <tr>
    <td>one</td><td>two</td><td>three</td>
  </tr>
  <tr>
    <td>this is a very very long text to show what i want to achieve</td><td>two</td><td>three</td>
  </tr>
</table>
</div>

Thank you in advance for your assistance!

Answer №1

Could this be what you're looking for? Take a look below.

https://jsfiddle.net/Tanikimura/4vypvwcn/

Implement text-overflow on a paragraph tag.

table{
  width:100%;
}
td {
max-width: 150px !important; 

}
td p{

text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
      padding: 3px 5px;
}
<div style="width:400px;display:block;">
<table>
  <tr>
    <td>one</td><td>two</td><td>three</td>
  </tr>
  <tr>
    <td><p>this is a very very long text to show what i want to achieve</p></td><td>two</td><td>three</td>
  </tr>
</table>
</div>

Answer №2

If the content in some columns is too large, it's difficult to size it relative to the content itself. The best approach would be to use the max-width method you selected. You could consider applying a specific class to the columns with larger content to make them more relatively sized. Targeting a particular child td of a tr may be necessary if only a few columns have oversized content. Otherwise, applying max-width to all columns would be the way to go.

Answer №3

I'm currently brainstorming a JavaScript solution for this issue, but there's definitely room for improvement. If anyone has any suggestions on how to enhance it, please feel free to share in the comments.

const table = document.getElementsByTagName('table')[0];

shrinkCells(table, .75);

function shrinkCells(tbl, maxWidth) {
  // Check if it fits within the parent
  if (tbl.offsetWidth <= tbl.parentElement.offsetWidth || maxWidth < .2) {
    return tbl;
  }
  // set the maxWidth for every element that is bigger than the current maxwidth
  Array.from(table.getElementsByTagName('td')).forEach(function (el) {
    if (el.offsetWidth > (tbl.offsetWidth * maxWidth))
      el.style.maxWidth = (tbl.offsetWidth * maxWidth) + "px";
  });
  
  shrinkCells(tbl, maxWidth - .05);
}
table{
  width:100%;
  border-collapse: collapse;
}
td{
  border: solid 1px #000;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  padding: 3px 5px;
}
<div style="width:400px;display:block;">
<table>
  <tr>
    <td>one</td><td>two</td><td>three</td>
  </tr>
  <tr>
    <td>this is a very very long text to show what i want to achieve asdhudfaslkjdfhdf asdf asdfasdfa asdf asdfasdf asdf a</td><td>two asdf asd fasd fasd fradfsddf asdf asdf asd fdsaf</td><td>three</td>
  </tr>
</table>
</div>

This code was created just for fun. Any feedback on how it can be enhanced would be greatly appreciated.

Answer №4

After extensive trial and error for nearly 5 years, I have yet to discover the perfect solution using tables. However, I did manage to find a workaround by utilizing grid and its auto width columns:

grid-template-columns: repeat(3, auto);

.grid{
    width:100%;
    display:grid;
    grid-template-columns: repeat(3, auto);
}
.grid div{
    /*max-width: 150px !important; */
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
    padding: 3px 5px;
}
<div style="width:400px;display:block;">
  <div class="grid">
    <div>one</div><div>two</div><div>three</div>
    <div>this is a very very long text to show what i want to achieve</div><div>two</div><div>three</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

The Django server fails to display the CSS files upon activation

Despite having all the static files in place, only the plain HTML loads without any styles for some unknown reason. I've attempted using collectstatic and even setting up a new project, but to no avail. STATIC_URL is also properly specified along with ...

Issue with Selenium WebDriver: Expectation failure while waiting for element visibility at specified location(..)

I'm facing a little issue with my automated test. Whenever the test encounters an error like this: Expected condition failed: waiting for visibility of element located by(...) I find it difficult to pinpoint the exact problem. @BeforeMethod pub ...

Ensuring the validity of float and non-empty values in JavaScript

Embarking on the journey of web development, I'm delving into basic applications. My current project involves creating a straightforward webpage to add two numbers and implementing preliminary validations - ensuring that the input fields are not left ...

Netlify deployment is failing to display the CSS styling on a website built with Hugo

Currently in the process of creating my own website using the "Call Me Sam" hugo theme. Everything looks great locally but once deployed on Netlify, the CSS styling seems to be completely disregarded. If you want to check out my repository: https://github ...

How to target the following sibling element (not a child) with CSS

I am working with the following HTML structure: <div class="col-sm-12"> <input id="my_id"> <div class="col-sm-1 col-3-box" style="position:absolute; margin-left:340px;"> </div> </div> How can I target and change ...

Exploring Web Scraping Through Dual System Security

I come seeking guidance on how to navigate a website with two different security systems in place. The first system requires a username and password, which I have successfully managed to handle. However, the second security system only requires a password ...

Can you guide me on implementing CSS Houdini in Next.js?

Exploring the world of CSS Houdini in my Next.js project has been quite an adventure. After successfully installing the necessary CSS Houdini package and css-paint-polyfill using yarn, I decided to follow the webpack guidelines provided at . Below is a sn ...

Adjust the vertical alignment in Material UI Grid to allow for proper tab navigation while maintaining the original order

When using Material-UI's standard grid system, the alignment of a new grid item after all 12 "space units" are utilized is based on the longest element within those 12 "space units". Is there a way to disrupt this type of alignment? If you take a look ...

Sort data by checking either multiple or single checkbox options in AngularJS; if none are selected, display all results

My goal is to implement a filter in my AngularJS code that will filter data based on selected checkboxes. If no checkbox is selected, all results should be displayed without any filtering. Currently, the issue I am facing is that the data is only displayed ...

Load the listbox with information retrieved from the database

<?php ini_set("display_errors","on"); $conn = new COM("ADODB.Connection"); try { $myServer = "WTCPHFILESRV\WTCPHINV"; $myUser = "sa"; $myPass = "P@ssw0rd"; $myDB = "wtcphitinventory"; $connStr = "...conn string..."; $conn-&g ...

Tips for personalizing the color scheme of Material UI Stepper Step?

I need help customizing the disabled Step color for Material UI Steppers. The default colors are Blue for enabled steps and Grey for disabled steps, but I want to change it to a different color as shown in this example: https://i.stack.imgur.com/HGGxp.png ...

Tips for enabling autoplay for videos in Owl Carousel

I am facing an issue with implementing autoplay functionality for videos in an owl carousel. Despite trying different solutions found online, including this Owl Carousel VIDEO Autoplay doesn’t work, I haven't been able to make it work. Additionally, ...

Can we add to the input field that is currently in focus?

Recently, I've been working on a bookmarklet project. My goal is to append an element to the currently focused input field. For instance, if a user clicks on a textarea and then activates my bookmarklet, I want to insert the text "Hello" into that sp ...

Fade in background color with jquery when scrolling

Is there a way to make the header background fade in after scrolling a certain number of pixels? The code I have sort of works, but not quite right. Any suggestions? Thank you! $(function () { $(window).scroll(function () { $(document).scrol ...

Styling certain UL and LI elements with CSS properties

Greetings everyone! I constantly struggle when it comes to making my CSS cooperate. I have some code that involves using ul and li tags. However, I only want to apply that styling to specific sections of my HTML code rather than all instances of the ul and ...

The values in my JavaScript don't correspond to the values in my CSS

Is it possible to retrieve the display value (display:none; or display:block;) of a div with the ID "navmenu" using JavaScript? I have encountered an issue where I can successfully read the style values when they are set within the same HTML file, but not ...

How to fix the issue of the mobile Chrome bar occupying part of the screen height in CSS

I am encountering a well-known issue with my collapsible scrollable bar implemented in Bootstrap. The problem occurs when scrolling on mobile devices, as the search bar takes up space from the sidebar's 100% height, causing the scrollbar to not reach ...

Using a color as a substitute for a background image on mobile devices

Is there a way to create a fallback in my CSS for changing the background image to a color when viewed on a mobile browser once the pixels reach the max-width? In the snippet below, the media query "only screen and (max-width: 600px)" works if the top bod ...

What purpose does the div tagged with the class selection_bubble_root serve in Nextjs react?

Just starting out with Nextjs and setting up a new Next.js React project. I used create-next-app to initialize the code base, but then noticed an odd div tag with the class 'selection_bubble_root' right inside the body. Even though its visibility ...

Using VBA to Populate Dropdown List on Webpage from an iFrame

I am facing an issue with my code that aims to interact with a webpage by clicking on a link and then modifying dropdown lists within an Iframe. Specifically, I am attempting to populate the Manufr dropdown list based on data from the Year iFrame using VBA ...