I am trying to align a bunch of variable width divs in a horizontal flexbox using auto margins. I can't use justify-content: space-around
, because of the Chrome-related issue I detailed in this question.
The divs that I am trying to align may contain other elements with variable-length text, so I used display: table
to allow them to expand. I set a base width of 100 pixels on the divs, so that they don't get too thin if there isn't much text. However, Chrome seems to calculate the auto margins based on the base width of the divs, rather than the calculated width if they are expanded by inner text. There is too much space between them, causing them to overflow the container even when they could fit within it.
Here is a Codepen with an example of my problem.
var ITEM_WIDTHS = [350,250,110,370,110,150,400,150,170];
var ITEM_LABELS = [
"zzzzzz",
"zz",
"zzzz",
"zzzzzzzzzzzz",
"zzzz",
"zzzzzzzzzzzzzzzz",
"zzzzzzzz",
"zzzzzzzzzzzzzz",
"zz",
];
function createConsistentWidthItems(items) {
var i, div;
for (i = 0; i < ITEM_WIDTHS.length; i++) {
div = document.createElement("div");
div.setAttribute("class","item");
div.setAttribute("style","width: " + ITEM_WIDTHS[i] + "px; min-width: " + ITEM_WIDTHS[i] + "px;");
div.innerHTML = i + "";
items.push( { element: div } );
}
}
function createConsistentlyLabeledItems(items) {
var i, div;
for (i = 0; i < ITEM_WIDTHS.length; i++) {
div = document.createElement("div");
div.setAttribute("class","item");
div.innerHTML = i + ITEM_LABELS[i];
items.push( { element: div } );
}
}
function fillItemContainer(items, itemContainer) {
for (var itemIndex in items) {
itemContainer.appendChild(items[itemIndex].element);
}
}
function generateItemRows() {
var items = [];
createConsistentWidthItems(items);
var itemContainer = document.getElementById("itemContainer1");
fillItemContainer(items, itemContainer);
items =[];
createConsistentlyLabeledItems(items);
itemContainer = document.getElementById("itemContainer2");
fillItemContainer(items, itemContainer);
}
window.onload = generateItemRows;
.item-container {
padding: 0;
margin: 20px 0;
border: 4px solid black;
width: 1500px;
display: flex;
overflow: scroll;
}
.item {
background: tomato;
border: 2px solid black;
padding: 5px;
width: 100px;
min-width: 100px;
height: 100px;
margin: 10px auto;
line-height: 100px;
color: white;
font-weight: bold;
font-size: 2em;
text-align: center;
display: table;
}
<h1>Items given fixed widths</h1>
<h2>Since they overflow the container, there are no margins</h2>
<div id="itemContainer1" class="item-container"></div>
<h1>Items given minimum width, but allowed to grow variably to fit text</h1>
<h2>Even though they shouldn't overflow the container at all, the margins cause them to do so</h2>
<div id="itemContainer2" class="item-container"></div>
Is there some CSS-only trick that I could use to get around this?