Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to style just one type of input field without also affecting other input types with CSS

Tags:

html

css

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).

like image 783
James Avatar asked Jun 12 '10 23:06

James


3 Answers

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.

like image 199
BoltClock Avatar answered Oct 03 '22 22:10

BoltClock


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.

like image 21
James Skidmore Avatar answered Oct 03 '22 22:10

James Skidmore


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 */ }
like image 44
artlung Avatar answered Oct 03 '22 21:10

artlung