How to display multiple elements side by side in a list item – CSS

What I want to do

I tried to display three elements (an icon, a title and a time) in each item in a list. Finally, I found I can use “display: flex” style in a list item so that the list displays these three elements side by side.

In this post, I would like to explain how I made this with Javascript and CSS.

Sample code – Javascript

I implemented the Javascript code like this. The const variable “listItem” is an item of the list. It has three elemets as an innnerHTML.

const listItem = document.createElement("li");

listItem.innerHTML = `
    <img src="${faviconUrl}" alt="Favicon">
    <span class="listTitleStyle">${urlTitle}</span>
    <span class="listDateTimeStyle">${visitTime}</span>`;

Sample code – CSS

  • display: flex
    The most important thing is to use “display: flex” in the “li” (list item) style. To do so, this “li” turns into the flexbox containar.
  • flex-shrink: 0
    flex-shrink is a CSS property used inside a flex container.
    It controls whether an item is allowed to shrink when there isn’t enough space in the container.
    0: Do not allow this item to shrink.
    1 (Default): The item will shrink if needed to fit the row.
  • flex-grow: 1
    flex-grow values are the ratio they grow in inside the containar.
    For example, there are three items. In this case, item1 gets 25% of the extra space, item2 gets 50% of the extra space and item3 gets 25% of the extra space.
    .item1 { flex-grow: 1; }
    .item2 { flex-grow: 2; }
    .item3 { flex-grow: 1; }

li {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 4px 8px;
    white-space: nowrap;
}

li img {
    width: 16px;
    height: 16px;
    flex-shrink: 0;
}

.listTitleStyle {
    flex-grow: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.listDateTimeStyle {
    flex-shrink: 0;
    margin-left: 8px;
    color: #888;
    font-size: 0.9em;
}

.no-bullets {
    list-style: none;
    padding: 0;
    margin: 0;
}


Comments

Leave a comment