CSS cascading rules for html controls

why CSS rules do not cascade down automatically to HTML controls like input or select and style the display of text in them?

For Ex: I have a css class applied on the body tag that renders text in red. Due to cascading rules, all the text in that html document is rendered in red (unless overridden). But if i have a textbox control in that document, the style does not cascade into the textbox to render the text in it in red.

Could someone point me to a reference document that talks about that??

Answers


The reason is the default CSS styles as determined by your browser.

  • input and select have default colors/sizes/padding etc.
  • Most other elements use inherit for color and size.
  • Another example is the font-size of table which is fixed and not inherited by default, and must be overridden by the developer.

Try this example HTML:

<html>

<style type="text/css">
body { color:red; font-size:36px; }
</style>

<body>
Hello
<input type="text" value="test value"/>
<table><tr><td>cell value</td></tr></table>
</body>
</html>

You will see that the font-size and color were not inherited by the input. Also, the cell value stayed at the default font size. Now add the following CSS to the style block:

input { color:inherit; font-size:inherit; }
table { font-size:inherit; }

You'll see that they inherit as you expected now.

What you really want to do is use a reset stylesheet. Tables are just one element that has a default style attached that isn't desirable for many developers, and every browser might be slightly different. This is why many make use of reset css stylesheets. These stylesheets reset most elements to uniform sizes and zero margins, padding, etc. Some are more extreme than others. See http://meyerweb.com/eric/tools/css/reset/ or Google for an example.

Since most reset stylesheets don't make colors of input and select inherit (most developers don't want them to inherit and instead want to explicitly set size/color), you should set them in your stylesheet:

input, select { ... }

Be careful with * { ... } for any purpose (as suggested by the other answer). This breaks the "cascading" part of CSS and will cause rules not to cascade as you would expect in nested elements. If you use * { color:red; } and then have the following HTML:

<h1 style="color:green;">Hello <i>world</i></h1>

You will end up with a green Hello and a red world. (Because the <i> matches *. Any new element will reset the style back to red, and color no longer cascades at all!)


Need Your Help

Storing SAS data (including table structure) in a single flat file

sas flat-file table-structure

I need to convert SAS data tables into flat files (or "ASCII files" as they were called once, as opposed to binary files). And only one flat file for each original SAS table.