Posts Tagged apply selectors to input css

Date: Ekim 7th, 2009
Cate: CSS

Advanced CSS Basics: How to apply CSS Selectors to INPUT element based on the Type attribute

Some days ago I though I was a successful person with CSS while talking with Rido about a new project we are developing now in our team, and regarding some “design” tasks I was assigned to.

But today I had a really annoying issue related to CSS. I needed to apply different styles to an HTML button and an HTML textbox; of course this is really simple by creating a CSS Class and applying it to each input by using the class attribute included in each element. This is an obvious solution, but it’s not the cleanest one because of the amount of time needed to add each class attribute to each HTML element and the bytes needed to do this (imagine one hundred input boxes without style and how much work will involve to apply styles to all of them)

What I wanted was something as easy as a CSS selector applied to any other HTML tag, something like INPUT.Text {background-color:red;}, something clean, small and easy to apply. Obviously I tried that, but it didn’t worked, so I googled until I found the solution.

With Internet Explorer 5 or above (yes, we are attached to IE for this development, but that’s not strange when working in a project in Microsoft) you can use CSS expressions in your CSS file. This expressions can be fully logical expressions, for example:

1. To assign the width of a table to the half of the body width
TABLE { width: expression(document.body.style.width / 2); }

2. To give Input Buttons a Fore color and the rest of Inputs a distinct Fore color by using only one CSS selector
INPUT { color: expression(this.type==”button”?’red’:'black’); }

Of course, expressions can be nested, and this solved my issue with CSS. After this new bit of knowledge I can see big new uses and optimizations for CSS that before I just thought to be impossible. And it’s also important to have Firefox in mind, so I also checked how to do this although this was much easier than for IE:

1. You can apply a kind of selection language (similar to xpath) and achieve the same result as my second IE example by using the following CSS selector:
INPUT { color: black; }
INPUT[type="button"] { color: red; }

Hope anyone finds this piece useful… It was quite hard for me to find a simple way to do it clean and non time-consumer with CSS.

Incoming search terms for the article: