Home > Software engineering >  CSS Table uniform column widths
CSS Table uniform column widths

Time:06-27

Is there a way to get a table with equal column width without specifying the overall table width and without specifying the individual column widths?

In other words, have every column be the width of the widest column - without knowing in advance the width of that widest column?

(And, I guess I mean without waiting for the table to render, then finding the width of each column, then have JS set the widths of all columns to that largest width).

CodePudding user response:

.grid-container {
  display: grid;
  grid-template-columns: auto auto auto;
  background-color: #2196F3;
  padding: 10px;
}
.grid-item {
  background-color: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(0, 0, 0, 0.8);
  padding: 20px;
  font-size: 30px;
  text-align: center;
}
<div >
  <div >1</div>
  <div >2</div>
  <div >3</div>  
  <div >4</div>
  <div >5</div>
  <div >6</div>  
  <div >7</div>
  <div >8</div>
  <div >9</div>  
</div>

An alternative solution to the table could be a CSS grid system. You can solve using CSS grid if you want

https://www.w3schools.com/css/css_grid.asp

.grid-container {
  display: grid;
  grid-template-columns: auto auto auto;
  background-color: #2196F3;
  padding: 10px;
}
.grid-item {
  background-color: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(0, 0, 0, 0.8);
  padding: 20px;
  font-size: 30px;
  text-align: center;
}
<div >
  <div >1</div>
  <div >2</div>
  <div >3</div>  
  <div >4</div>
  <div >5</div>
  <div >6</div>  
  <div >7</div>
  <div >8</div>
  <div >9</div>  
</div>

CodePudding user response:

I don't think you can do it with <table>, but you can do it with display: grid.

.a {
  display: inline-block;
}
.a>div {
  display: grid;
  grid-template-columns: repeat(5,1fr);
  gap: 2px;
}
.a>div>div {
  border: 1px solid silver;
}
<div >
  <div>
    <div>1</div>
    <div>22</div>
    <div>333</div>
    <div>4444</div>
    <div>55555</div>
    <div>66</div>
    <div>7777</div>
    <div>888888</div>
    <div>99999999</div>
    <div>0000000000</div>
  </div>
</div>

  • Related