5

Is there a way to write style rules that will only influence text fields. Suppose I have the following:

<div id="helloDiv">
<input type="text" name="something" /><br />
<input type="checkbox" name="somethingElse" /><br />
<input type="submit" name="go" />
</div>

div#helloDiv input {
   border: 1px solid red;
}

The problem with the above CSS rule is that it will affect ALL input fields not just input text but also radio buttons, submit buttons, etc.

So is there a cross browser solution to affect just one type of input field within a div or other page element (without resorting to assigning the input fields styles individually).

James
  • 53
  • 1
  • 3

3 Answers3

4

The most tedious but IE6-compatible way to do it is to give all your input type="text" elements some specific CSS class, like class="text", and targeting that class only:

div#helloDiv input.text {
    /* Styles */
}

The simplest, CSS2.1 but IE6-incompatible way is just

div#helloDiv input[type="text"] {
    /* Styles */
}

without modifying your HTML.

Addendum: per animuson's comment, choose either one of these. Decide whether or not you need or want to support IE6, and take the appropriate code.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • Bordering on egotistic here, but, thanks to @Mark and whoever else upvoted for helping me break 1k rep :P – BoltClock Jun 12 '10 at 23:44
  • The 1st method actually doesn't work on the latest version of ff which is what I am using here. But the 2nd works. – James Jun 12 '10 at 23:49
  • It should work. Make sure you include both `type` and `class` attributes: `` – BoltClock Jun 12 '10 at 23:54
  • 2
    @James: Then you're not doing it right... Also, you should never implement both of these at once, that's so redundant. That's like applying two of the same exact class to that element. Either say "Screw IE6" and go with the attribute selector or go with the class names, *don't* use both. – animuson Jun 12 '10 at 23:58
  • Oh never mind, I was implementing it wrong. I didn't add the class="text". I didn't want to use that to begin with so I am going with method 2. – James Jun 13 '10 at 00:01
2
input[type=text] {}

It's not compatible in IE6, but most other browsers. To make it completely cross-browser compatible, you will need to either apply a common class to all of the inputs of the same type or use JavaScript. See here.

Community
  • 1
  • 1
James Skidmore
  • 49,340
  • 32
  • 108
  • 136
1

You can use an attribute selector, that looks like this:

input[type=text] {
  /* stuff */
}

Now, support for this does not extend to Ye Olde IE6. So, many people simply bite the bullet and add classes to their inputs to style them. Then, you can set common styles to your inputs and then changeup for specific kinds. So, something like:

input { /* common styles */ }
input.mySubmit { /* only submit */ }
input.myText { /* only text */ }
artlung
  • 33,305
  • 16
  • 69
  • 121