css table element gets stretched if only a single element exists

Viewed 45

I have a styling problem. When I only create a few elements, the element gets stretched. It only occurs when there are not enough elements to fill a single row. After the first row is filled it has no problems.

What do I need to change in the CSS or can I use js to calculate how many elements would fit into one row?

function create_elem(){
  const parent = document.getElementById("parent");
  let element = document.createElement('div');
  element.innerHTML = '<a href=""><div class="card"><img src="https://www.oreilly.com/library/view/html-css-and/9780133795165/graphics/9780133795189.jpg" alt=""> <div class="title"><h1>Title</h1></div></div></a>';
  parent.append(element);
}

function empty_parent() {
  const parent = document.getElementById("parent");
  while (parent.hasChildNodes()) {
    parent.removeChild(parent.firstChild);
  }
}

function get_selector(){
  const select = document.getElementById("select");
  let value = parseInt(select.value);
  if (!select.value || select.value == "") value = 0;
  return value;
}

function setSize(num) {
  empty_parent();
  for(let i = 0; i < num; i++){
    create_elem();
  }
}
.container {
    width: 100%;
    height: 90vh;
    background:rgba(0,0,0,.1);
}
#parent {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    grid-column-gap: 1rem;
    grid-row-gap: 2rem;
    overflow: auto;
}
img {
    width: 100%;
    height: 35vh;
    object-fit: cover;
    border-radius: 5px;
    margin-bottom: 1rem;
}
<div class="set__size" >
  <input id="select" type="number" />
  <button onclick="setSize(get_selector())">Submit</button>
</div>
<div class="container" id="parent" />

1 Answers

You can remove the "width: 100%" from img and add a card class to center for example :

.card {   
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

.card img {
    height: 35vh;
    object-fit: cover;
    border-radius: 5px;
    margin-bottom: 1rem;
}
Related