Home > Software design >  CSS rules for elements with less than x Width
CSS rules for elements with less than x Width

Time:03-08

Any way to add rules for input elements that are < 200px ?

<input style="width 200px" value="normal input" />

<input style="width 20px" value="20" />
<input style="width 20px" value="10" />
<input style="width 20px" value="2022" />

Now CSS ->

input(width > 200px) {
    text-indent: 20px;
    background: red;
}

input(width < 200px) {
    text-indent: 0;
    background: white;
}

CodePudding user response:

You can use class

input.width-200px {
    width: 200px;
    text-indent: 20px;
    background: red;
}

input.width-20px {
    width: 20px;
    text-indent: 0;
    background: white;
}
<input  value="normal input" />

<input  value="20" />
<input  value="10" />
<input  value="2022" />

CodePudding user response:

here is an example to select the input with style property

input[style="width: 200px"] {
    width: 200px;
    text-indent: 20px;
    background: red;
}
<input style="width: 200px" value="normal input" />

<input style="width: 20px" value="20" />
<input style="width: 20px" value="10" />
<input style="width: 20px" value="2022" />

CodePudding user response:

There is no way of doing this in CSS.

[It can work for the very specific examples you gave, but not in the general case when several different widths might be involved and where several different methods of them being set might be involved].

The only thing for it seems to be to plod through all the input elements whenever a change is made to the content/layout during run time.

Also as you may not know whether alternative widths have been set inline in style attributes or via style sheets, maybe using important, or using CSS variables, I think you have to set the desired styling inline.

Here's a simple snippet to do this. It needs to be run whenever a change is made at run time so you may want to introduce a mutation observer, or (hopefully) you may know that this won't be needed.

const inps = document.querySelectorAll('input');
inps.forEach(inp => {
  if (window.getComputedStyle(inp).width.replace('px', '') < 200) {
    inp.style.textIndent = '0';
    inp.style.background = 'white';
  } else {
    inp.style.textIndent = '20px';
    inp.style.background = 'red';
  }
});
<input style="width: 200px" value="normal input" />

<input style="width: 20px" value="20" />
<input style="width: 20px" value="10" />
<input style="width: 20px" value="2022" />

Note: you may find you need to set important as well if that has been used somewhere.

  •  Tags:  
  • css
  • Related