Giffyguy Giffyguy - 4 months ago 5x
CSS Question

How do you set the CSS styles of child elements from within the parent's style attribute?


<img src=""><br />
<img src=""><br />

Due to the structure of my dynamic ASP.NET code generation, I would prefer to avoid using pre-defined CSS classes. These attributes will vary from one webcontrol to another, and cannot be set globally in the
sections. For example, I might have two of my webcontrols on a single page, each with different CSS attributes set for all of their child-images.

As a last resort, I can piece together a dynamic CSS class generator for these controls - but that would be a giant pain, with really sloppy results. Namely, each webcontrol would generate their own CSS class, write it in the
sections somehow, all while making sure that multiple webcontrols aren't using the same name for their CSS classes. Like I said, a giant sloppy mess - hence I'd love to be able to cram all this information into the attribute tags for the individual controls, so they don't step on each-other's toes.


Could you make something like this:

 <div id="yourcontrol_1">
    <img src="/some/image.jpg">

and then define the styles in a stylesheet - not inline:

#yourcontrol_1 img {
    border: 20px double red;

That way, whatever you specify only applies to the img tags that are children of id yourcontrol_1.

This level of control is not possible with inline styles, IIRC.

If you have no way of determining the classname/id beforehand, you could still generate them, and embed the styles using the style tag. As you say: not pretty, but it would work.

       #generated_identifier_0xcafe img {
          padding: 200em;
       #generated_identifier_0xbeef img {
          background-color: green;
     <div id="generated_identifier_0xcafe">
         <img src="someimage.png">
   <!-- etc... -->