Home > Software design >  Aligning key colon value data in css without using HTML table?
Aligning key colon value data in css without using HTML table?

Time:03-01

I have the following data that I want to show. Ideally I want the keys and values left aligned, separated with colons in the middle.

I want the result to be like the following:

key1  : value1
key2  : value2
keyAbc: Value Abc
key_N : value N

And not like the following:

key1: value1
key2: value2
keyAbc: Value Abc
key_N: value N

How to do this in CSS or SCSS, and not using HTML table?

CodePudding user response:

You can use grid, making the columns take on the max width of content.

This snippet adds the colons in a pseudo element as they seem to be just a visual clue rather than part of the data.

Of course you will want probably to add some padding to suit your particular requirements.

.table {
  display: grid;
  grid-template-columns: max-content max-content;
}

 .table > *:nth-child(even)::before {
   content: ":";
}
    
<div >
<div>key1</div>
<div>value1</div>
<div>key2222222</div>
<div>value2</div>
<div>key3</div>
<div>value3</div>
</div>

CodePudding user response:

Just use the inline-block and make sure the children of the main DIV gets that too and it will automatically resize based on widest width, much like table. No need for flex.

 
.inline-block {
display: inline-block;
}

.inline-block > div {
margin: 2px;
padding: 1px; 
}


    
<div >
<div>key1</div>
<div>keykey2</div>
<div>key3</div>
</div>
    
<div >
<div>:</div>
<div>:</div>
<div>:</div>
</div>

<div >
<div>value1</div>
<div>value2</div>
<div>Value3</div>
</div>

CodePudding user response:

If you're using div structure, you can use display: flex and could do something like this:

.css-table {
  display: flex;
}

.key {
  width: 10%;
}

.val::before {
  content: ': ';
}
<div >
  <div >key1</div>
  <div >value1</div>
</div>
<div >
  <div >key2111</div>
  <div >value2</div>
</div>
<div >
  <div >key3</div>
  <div >value3</div>
</div>
<div >
  <div >key4</div>
  <div >value4</div>
</div>

If you don't want to specify width, you'll need use JavaScript to calculate the width and apply it inline.

let maxWidth = 0;
  
// Calculate maxWidth
document.querySelectorAll('.css-table').forEach(function(cssTableEl) {
  cssTableEl.querySelectorAll('.key').forEach(function(keyEl) {
    let currWidth = keyEl.clientWidth;

    if (currWidth > maxWidth) {
      maxWidth = currWidth;
    }
  });
});


// Apply maxWidth
document.querySelectorAll('.css-table').forEach(function(cssTableEl) {
  cssTableEl.querySelectorAll('.key').forEach(function(keyEl) {
    keyEl.style.width = maxWidth   'px';
  });
});
.css-table {
  display: flex;
}

.val::before {
  content: ': ';
}
<div >
  <div >key1</div>
  <div >value1</div>
</div>
<div >
  <div >key2111</div>
  <div >value2</div>
</div>
<div >
  <div >key3</div>
  <div >value3</div>
</div>
<div >
  <div >key4</div>
  <div >value4</div>
</div>

  • Related