Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to reference an existing CSS style from another CSS style using CSS or javascript?

If I have a style defined

.style1
{
   width: 140px;
}

can I reference it from a second style?

.style2
{
   ref: .style1;
}

Or is there a way via javascript/jQuery?

--- Edit

To clarify the problem, I am trying to apply whatever style is defined for a #x and #c to .x and .c without altering the CSS as the CSS is going to have updates that are out of my control.

I used width but really the style would be something more complex with font, border and other style elements being specified.

Specifying multiple class names does work when the style is being applied to a class so I'll mark existing responses as answers, but I need to take the style being applied to an id and also apply it to a class style ... if that makes any sense.

like image 331
JTew Avatar asked Oct 08 '08 03:10

JTew


People also ask

How do I reference an external style sheet in CSS?

External CSS With an external style sheet, you can change the look of an entire website by changing just one file! Each HTML page must include a reference to the external style sheet file inside the <link> element, inside the head section.

How would you reference the CSS file style CSS from an HTML file in the same folder?

However, if the css file is in another directory (say inside a folder called css) you would need to type out the path to it relative to the html document. In this case, you'd type "css/style. css".

How do I link another CSS file?

Note: There are two different ways to import a CSS file into another using @import url(“style2. css”); or @import “style2.

In what way can you reference CSS?

Link to External CSS External style sheets can be referenced with a full URL or with a path relative to the current web page.


2 Answers

There's no way to do it with CSS -- it's an oft-requested feature, but not included in the spec yet. You also can't do it directly with JS, but there's sort of a hacky workaround:

$('.style2').addClass ('style1');
like image 185
John Millikin Avatar answered Oct 03 '22 23:10

John Millikin


you can achieve the same functionality by allowing elements to inherit multiple styles. ex.

<p class="style1 style2">stuff</p>

and then your css would include, for example:

.style1 {width:140px;}
.style2 {height:140px;}

edit: actually robert's answer might better approximate the method you are trying to achieve

.style1, .style2 {width: 140px;}
.style2 {height: 140px;}

<p class="style2">i will have both width and height applied</p>
like image 21
Owen Avatar answered Oct 03 '22 22:10

Owen