views:

899

answers:

3

Two parts to my question:

1) Is there a way to inherit another control's attributes and styles in CSS? Assume the controls have no parent/child hierarchy and can be completely different control types:

IE:

#MyFirstControl
{
  width: 100px;
}

#MySecondControl
{
  width: MyFirstControl.styles.width; /* This doesn't work */
}

2) Assume a Label tag is a child of any other tag. The width attribute will neither work with "inherit" nor "auto". What's wrong?

IE:

<style>
  div
  {
    width: 100px;
  }
</style>

<div>
  <!-- This label does what it wants for width. It's not the width of the containing div -->
  <label style="width: inherit">Some Text</label>
<div>
+2  A: 

Part 1: you want to use class names, not ids, to control the styles:

.control_a {
  width: 100px;
}

<blah id='MyFirstControl' class='control_a'/>
<blah id='MySecondControl' class='control_a'/>

This lets you share styles across any number of tags. Also, keep in mind, you can use more than one class name on a single element:

.control_a {
  width: 100px;
}

.red { background: #f00; }    
.blue { background: #00f; }

<blah id='MyFirstControl' class='control_a red'/>
<blah id='MySecondControl' class='control_a blue'/>

This lets you select many different sources of style for a single element.

Ned Batchelder
Thanks for your answer and time Ned. I use classes quite a bit. I didn't give any indication, but I do know CSS pretty well. This was more philisophical than anything. I was attempting to address an issue with CSS vs. JavaScript manipulation of control attributes. Thanks man!
Boydski
+1  A: 

There is no way to inherit CSS "objects". You can inherit styles from tags inside other tags, but it is the tag inheriting and not the style itself. If you place a tag inside a tag with another style, it will inherit from that style.

It might be interesting if CSS styles were treated as objects, as you could avoid a lot of coding, but since you can create a class that can be applied to disparate types of objects, and even apply multiple classes to a tag, it is more interesting than necessary.

I am not sure about the second question, but I would imagine it has to do with the fact you are applying to a tag name, and not using a class or id. I would have to play with it some more to see if I can figure something out.

Gregory A Beamer
A: 

1) Since CSS doesn't allow for self-reference you could have common aspects of two separate elements specified in the same style:

#MyFirstControl, #MySecondControl
{
  width: 100px;
}

2) If my IDE and browser are to be believed, inherit is not a valid value for width in that context but I'm not sure why. That might be why your example doesn't work.

Ax