Search code examples
javascripthtml-selecttext-indent

Get text indent of HTML select elements


At HTML Select elements there is around 4px indent.

How can I calculate/ get the exact value using JavaScript

I tried this but doesn't get me the correct value

const el = document.querySelector('select');
const computedStyle = getComputedStyle(el);
computedStyle.textIndent // '0px'
computedStyle.padding // '0px'

select-indent


Solution

  • I would try to determine based on CSS box model. In your case I would expect it to have a pading-left. You want the space from the select border to the text content. This is affected by the select padding, the option margin, the option border and the option padding.

    select = window.getComputedStyle(document.querySelector('select'))
    option = window.getComputedStyle(document.querySelector('option'))
    console.log(select['padding-left'])
    console.log(option['margin-left'])
    console.log(option['border-left'])
    console.log(option['padding-left'])
    <select><option>Item</option><select>