Home > front end >  CSS grid proper width for element in column
CSS grid proper width for element in column

Time:03-21

Trying to properly align some html elements with CSS grid, but can't seem to figure out how. I want all the element in the 2nd column to have equal width. But as soon as I give some width property to the select they get uneven. I can make all of them width:auto to align them, but I don't want unnecessary long inputs. I want the select to have width:fit-content and all the other element in that column to match that width. How do I do that?

#extend {
grid-auto-flow: column;
display: grid;
grid-template-columns: repeat(4, max-content);
grid-template-rows: repeat(3, max-content);
grid-row-gap: 0.1em;
grid-column-gap: .5em;
}

#extend>input[type="submit"] {
grid-row-start: 2;
}

select{
width: fit-content;
}
<div id="extend">
<label>Range</label>
<label>Times</label>
<label>Option</label>

<div>
    <label>0 to</label>
    <input type="text" id="einp">
</div>
<input type="text" id="etime">
<select id="repSel">
    <option>Test 1</option>
    <option>Test 2</option>
</select>
<input type="submit" value="Apply">
<input type="submit" value="Cancel"> 
</div>

CodePudding user response:

There are probably some default width settings for the input fields. Anyway, I don't think a grid built this way will work the way you want it to. I changed the structure with a flex box model, I hope to be useful.

HTML:

<div id="extend">

<div class='flex-col'>
<label>Range</label>
<label>Times</label>
<label>Option</label>
</div>
<div  class='flex-col mx-2 w-min-content' >
 <div class='d-flex'>
    <label class='text-nowrap mr-2'>0 to</label>
    <input type="text" id="einp" class='d-flex'>
 </div>

<div  class='d-flex my-1'>
<input type="text" id="etime">
</div>
<div  class='d-flex'>
<select id="repSel">
    <option>Test 1</option>
    <option>Test 2</option>
</select>
  
 </div>
 </div>
 <div  class='d-flex w-auto'>
 
 <input class='mr-2' type="submit" value="Apply">
<input type="submit" value="Cancel"> 
 
</div>
</div>

CSS:

#extend{
  display:flex;
  flex-direction:row;
 
}
.flex-col{
    display:flex;
  flex-direction:column;
   flex:0 0 auto;
       justify-content: space-between;
}
.d-flex{
  display:flex;
  align-self: center;
  width: 100%;
}
.d-flex input{
  display:flex;
  width:100%;
  min-width: 0; 
}
.w-min-content{
  width:min-content;
}
.text-nowrap{
  white-space:nowrap;
}
.w-auto{
  width:auto;
}
.mx-2{
  margin:0 .5rem;
}
.my-1{
  margin-top:.25rem;
  margin-bottom:.25rem;
}
.mr-2{
  margin-right:.5rem;
}
 
#repSel{
  width:fit-content;
}
label{
 display:block;
}

-> Link to jsfiddle

CodePudding user response:

I think what you are trying to do is give select element to have same width as the other input

select{
   width:100%;
}

codepen link

  • Related