Home > front end >  Equal column width not working when use text right in CSS Grid
Equal column width not working when use text right in CSS Grid

Time:11-10

I want the grid columns to be equal width whether it will be one, or two or more columns, Also the column gap must be same. I found one of the example but when use text-right for columns the column width seems not equal. Anyone help me to achieve this. img The following example column gap spacing and width not equal. I want achieve using CSS or JS.

.grid-equal-columns {
    display: grid;
    grid-auto-flow: column;
    grid-auto-columns: 1fr;
}
.grid-equal-columns > * {
    overflow: hidden;
    text-align: right;
    margin: 10px;
}
<div >
  <div>Sample</div>
  <div>12122</div><div>hello text</div> 
    <div>44444</div> 
  <div>5555</div><div>6666666666666666666666666</div>
</div>

</div>

CodePudding user response:

You need to provide fix width to your grid-column so, it's take fix width and your every column should be same.

<!DOCTYPE html>
<html>
   <style>
      .grid-equal-columns {
      display: grid;
      grid-auto-flow: column;
      grid-auto-columns: 1fr;
      }
      .grid-equal-columns > * {
      width: 50px;
      overflow: hidden;
      text-align: right;
      margin: 10px;
      }
   </style>
   <body>
      <div >
      <div>Sample</div>
      <div>12122</div>
      <div>hello text</div>
      <div>44444</div>
      <div>5555</div>
      <div>6666666666666666666666666</div</div>
   </body>
</html>

CodePudding user response:

grid-auto-columns: 1fr;

creates 1fr columns equally distributed to the grid. regardless how long your text will be in the the cell.

You can achieve two ways.

remove grid-auto-columns: 1fr;

.grid-equal-columns {
    display: grid;
    grid-auto-flow: column;
}
.grid-equal-columns > * {
    overflow: hidden;
    text-align: right;
    margin: 10px;
}
<div >
  <div>Sample</div>
  <div>12122</div>
  <div>hello text</div> 
    <div>44444</div> 
  <div>5555</div>
  <div> 6666666666666666666666666</div>
</div>

or use flexbox with justify-content: space-evenly

.grid-equal-columns {
    display: flex;
    justify-content: space-evenly;
}
.grid-equal-columns > * {
    overflow: hidden;
    text-align: right;
    margin: 10px;
}
<div >
  <div>Sample</div>
  <div>12122</div>
  <div>hello text</div> 
    <div>44444</div> 
  <div>5555</div>
  <div>6666666666666666666666666</div>
</div>

  • Related