Equally distribute grid column width inside container according to their content dimensions

I am facing a challenge with my side-by-side grid columns. I want the grid to always be the width of its container, ensuring that as much content from each column is visible as possible within that space.

In my demo, the grid is currently set at 300px wide with both columns being content editable for dynamic changes in length. Despite using

grid-template-columns: minmax(min-content, 1fr) minmax(min-content, 1fr);
, I have not been able to achieve the desired outcome.

When the total content width exceeds 300px, the grid overflows horizontally instead of automatically adjusting the column widths to fit accordingly:

https://i.sstatic.net/TcuT8.png

My goal is to constrain the grid's width to 300px and ensure that the widest cell shrinks enough to display as much content as possible from the smaller cell while applying overflow-x: ellipsis.

This balancing act should occur both ways: shrinking wider cells until proportional balance is achieved.

The existing CSS properties don't seem to allow for this behavior without depending on JavaScript calculations or complex solutions.

If anyone has a CSS-only solution or an alternative approach that requires minimal JavaScript intervention, I would greatly appreciate your input.

Answer №1

Here is a scenario where combining flexbox with grid proves to be the ideal solution. By placing a flex element within a grid row, you can easily achieve the desired grow and shrink capabilities with minimal css and no need for JS.

In the example provided below, the column containing the most content will expand without encroaching into the adjacent column, while the other column will shrink proportionally. The child elements of the flex container are configured to either grow and shrink equally (flex: 1 1) or occupy 150px (flex: 1 1 150) of available space if the content width is insufficient. The flex-basis is set to 150, which is half of the specified width. Adjust the flex-basis accordingly for wider widths.

*, ::before, ::after {
    box-sizing: border-box;
}

body {
    width: 300px;
}
    
html * {
    border: 1px solid black;
}

.flex-col {
    display: flex;
    flex-wrap: nowrap;
    gap: 1rem;
    
}

.flex-col > * {
    flex: 1 1 150;
}

.col {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}
<div class="flex-col">
        <div class="col" contenteditable>Lorem ipsum dolor sit amet consectetur adipisicing elit. </div>
        <div class="col" contenteditable>
            Alias, soluta Lorem ipsum dolor sit, amet consectetur adipisicing elit. Veritatis natus odio dolorum. Dolorem minus, labore distinctio eum praesentium eos ullam ducimus repellat, rerum vel eveniet soluta laborum odit odio sequi. </div>
</div>

Answer №2

It seems like your goal is to create a two-column grid with fixed widths where the column sizes adjust based on the content they hold (with text that overflows being truncated). While the code below can help you achieve this to some extent, there may be issues when the total text content exceeds the grid width. In such cases, the columns will not resize proportionally beyond the grid width. Additionally, if you intend to use contenteditable elements within your grid, certain browsers might stop displaying input once text starts overflowing due to the combination of overflow: hidden and text-overflow: ellipsis properties (resulting in seemingly empty columns with excess characters).

.grid {
  display: grid;
  grid-template-columns: repeat(2, auto);
  width: 300px;
}

.column {
  border: 1px solid gray;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
<div class="grid">
  <div class="column" contenteditable="true">
    abcdefghijklmnop
  </div>
  <div class="column" contenteditable="true">
    abcdefghijklmnopqrstuvwxyz
  </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

Use CSS to activate a sibling div when hovering over a button within the same div that contains the button

Is it possible to change the color of div #panel when hovering over the button #button inside div #left? #left #button:hover~#panel { background-color: blue; } #panel { position: absolute; float: r ...

Steps for adding a border to kendo grid row hover

One of my tasks involved creating a grid using Kendo, and I wanted to display borders on a grid row when the cursor hovers over it. I attempted the following code snippet: .k-grid > table > tbody > tr:hover, .k-grid-content > table > tbody ...

How can I troubleshoot the overflow-y problem in a tab modal from w3 school?

https://www.example.com/code-sample overflow: scroll; overflow-y: scroll; When I type a lot of words, they become hidden so I need to use overflow-y=scroll. Despite trying both overflow: scroll; and overflow-y: scroll;, I have been unable to achieve the ...

Tips for utilizing jQuery to display images similar to videos

Are there any plugins available that can create a video-like effect on images by incorporating scroll, pan, tilt, zoom (in/out) transitions for a few seconds before fading to the next image? I've searched but haven't found anything quite like thi ...

How can I connect a custom Web Resource button in Dynamics CRM 2015 to a specific function within a Javascript Library integrated into the form?

I have added a button to the form using the following code: <button type="button" onclick="btnCalculate_onClick();">test</button> Within the form, I have included a function called btnCalculate_onClick() from a Library named dc_btnAutofillAdd ...

Images are not loading properly on the website when viewed on an iPad

As I work on my website with a parallax effect, I recently came across an issue: images not displaying on iPod devices. Unfortunately, since I don't have access to an iPod, I am unable to verify this myself. Can anyone explain why the main pictures ar ...

The code functions properly when tested on a local server, but doesn't produce any results when

Currently, I am working on customizing a premade website and have been tasked with making a modification. The goal is to implement a confirmation box that appears when a button to delete a meeting task is clicked, rather than immediately deleting it. Afte ...

Click to switch CodeMirror's theme

http://jsbin.com/EzaKuXE/1/edit I've been attempting to switch the theme from default to cobalt and vice versa, toggling each time the button is clicked. However, I am facing an issue where it only switches to the new theme once and doesn't togg ...

Are all elements still displaying the menuBar style? Using the PHP include function, <?php include... ?>

Here is the Menu Bar code I am using: <!DOCTYPE html> <html> <link href = menuBarStyle.css rel = "stylesheet"> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"> <div class = "menu"> ...

Issue with CSS hover effect not being detected in IE 7 on a div element

Need some help with a top navigation setup for a website where I have a div inside an li element. Encountering issues in IE 7 where there are "holes" in the box causing the drop down to disappear when the user is still interacting with it. Initially trie ...

Creating an image overlay within HTML text in NSAttributedString with CSS: A step-by-step guide

I am currently working on extracting HTML text that includes a YouTube video. In order to showcase this video, I have implemented a preview image. The original text is as follows: <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do ei ...

CSS Flexbox - Choose all elements that appear at the start of a new line (Wrap)

Is there a CSS selector that can prevent content insertion on new lines when using the wrap feature in CSS-Flexbox? I am utilizing CSS-Flexbox for a layout with the wrap option, but I do not know the number of lines beforehand. I need a solution where the ...

Bring life to the process of adding and removing DOM elements through animation

I am seeking to provide an engaging and interactive experience for my users while ensuring responsiveness. To achieve this goal, I have decided to learn more about web development by creating a card game. My current setup involves clickable elements that ...

Deactivating Webkit Input Form Shadow

Similar Question: Looking to Remove Border on Input Boxes in Chrome? Is it possible to turn off the colorful shadow effect produced by Webkit browsers when a form field is clicked? The yellow shadow in Chrome and blue shadow in Safari can interfere wi ...

CSS technique to display background on hover

My website has a bootstrap 'More' dropdown feature on the left navigation bar. However, there is an unwanted background hover effect that I can't seem to remove. Despite removing all background hovers from my CSS, the issue persists. Can any ...

Customizing Bootstrap Navigation: Creating Space Between Menu Items

I've configured my Bootstrap navigation with a dropdown toggle for "Coverage". I'm looking to decrease the spacing between each list item (li) under this dropdown. What CSS setting should I use to achieve this? Interestingly, when I apply float: ...

Determining the position coordinates of an element in relation to the viewport using JavaScript, regardless of its relative positioning

I am currently developing a vueJs web application and I'm in need of determining the position of an element within my web app relative to the viewport itself, rather than its parent elements. I'm curious if there exists a function or property tha ...

Customize cursor using CSS

I have a div with overflow: hidden that I am making scrollable by allowing the user to click and drag the background. There are links and buttons within this space. Here is the CSS I am using for this: #div-grabscroll { cursor: url(../img/op ...

Understanding the response format in jQuery and AJAX

Can anyone advise on the optimal data format for communication with JavaScript? Should I stick to JSON or use plain HTML instead? Are there any alternatives worth considering? ...

Confirm that the phone number is in the correct format using HTML

Hello, I am attempting to validate a phone number using the following format: 080******** 081******** 082******** 083******** I have tried the following code: <input type="tel" name="signupMobileTel" placeholder="08121234567" size=11 pattern="/^(08( ...