Get text indent of HTML select elements

428 Views Asked by At

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

2

There are 2 best solutions below

1
Bob On BEST ANSWER

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>

0
JonoJames On

You on the right track

const el = document.querySelector('select');
const computedStyle = getComputedStyle(el);
var indent = computedStyle.textIndent ;
var padding = computedStyle.padding ;
var margin = document.getElementById("myDiv").style.margin;

Just assign them to variables also using query selector you could have more than one on the page so it would hide the specific one your looking for hence why I prefer to call things through and ID