How to customize a Select in columns?

Asked

Viewed 819 times

4

Guys I have a select that shows

CODE | TITLE | DESCRIPTION | UF

0001 | TESTE1 | NEW ITEM 1 | SP

0002 | TESTE2 | NEW ITEM ADD 2 | SC

See that the column is disfigured, I would like to align this with css, only managed to use fixed font (type Ourrier), but then destona the page.

I know there is how to do in DIV, but I wanted to know first if you have CSS in Select.

I searched the web, but I just found how to style colors and the like, but not the text in columns.

  • 1

    You want the lines of each option have those columns and are aligned vertically, that’s it?

  • Yes, I want to align the texts in the form of columns, when I bring the text that comes from a table I will leave all with the same number of characters matching each column. It would be like putting a table inside a select

1 answer

3


You have to use various tools, and yet committed to font.

First of all you must have a font that has the same width for all letters, otherwise it will be impossible to make those columns match.

Second (and if you don’t do that when you generate those strings) you have to compare all the lines, break into pieces and know which maximum width you need. Then you have to add spaces to the ones that are too short.

An example would be like this:

function gerarEspaco(qtd) {
    var str = '';
    for (var i = 0; i < qtd; i++) str += '&nbsp;'
    return str;
}

var options = [].slice.call(document.querySelectorAll('option'));
var partes = options.map(function(option) {
    return option.innerHTML.split(' | ');
});
var maximos = options[0].innerHTML.split(' | ').map(function(str, i) {
    var max = 0;
    partes.forEach(function(parte) {
        if (parte[i].length > max) max = parte[i].length;
    })
    return max;
});


options.forEach(function(option, i) {
    var html = partes[i].map(function(parte, j) {
        var emFalta = maximos[j] - parte.length;
        var novosEspacos = gerarEspaco(emFalta)
        return parte + novosEspacos;
    }).join(' | ');
    option.innerHTML = html;
});
console.log(maximos); // [6, 6, 14, 2]
option {
	font-family: monospace;
}
<select name="" id="">
    <option value="">CODIGO | TITULO | DESCRICAO | UF</option>
    <option value="">0001 | TESTE1 | NEW ITEM 1 | SP</option>
    <option value="">0002 | TESTE2 | NEW ITEM ADD 2 | SC</option>
</select>

jsFiddle: https://jsfiddle.net/nsjhce28/

  • Um... this method I already use... I already bring the size of each fixed column of a php result, and I already use monospace font, but I wonder if there is a more elegant way, so I see I will have to go to div with scroll

  • @Marcelo because, in this case it’s really with custom select. I thought you didn’t have the standard HTML spaces you put in the question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.