I am using a WordPress premium theme that has a 25.000+ lines styles.css. I want to change the font and main color sitewide, and for this I would like to catch ALL classes and IDs that use them for my childtheme.
Manually searching through 25.000 lines and then selecting and copying the classes together is a very slow procedure, and I am sure this can be automated with RegEx and the preg match all thing or the like, but I know too little about creating such a script.
But at least I could figure out the logic that a script for such a task would need to follow.
So let's say I need a rule that collects ALL classes and IDs to which the font Roboto is assigned.
Basically it needs to
1. find Roboto, then
2. go back to the { and
3. collect everything before { until
4. the last } before, so it needs to go backwards searching
5. This it needs to do through the whole document, to catch all classes to which Roboto is assigned.
The result will be a very big list of comma-separated classes which I can then easily assign the new font to.
Does any of the RegEx experts see the string already in front of his eyes? I am sure it is not that difficult for someone who "speaks" RegEx fluently, but I got soon lost trying to learn it myself, I only succeeded in simple replacments.
...
last CSS rule ending here.
}
.some,
.classes,
.and,
#IDs to collect them all,
#not only from this one css rule,
. but from a whole 25.000+lines stylesheet
{
font-family: 'Roboto', sans-serif;
font-size: 32px;
color: ...
etc.
}
...
There is currently no way of targeting all classes with a specific CSS Rule like font-family either with CSS, JavaScript, or jQuery
But, you can do searches for:
'begins with..'
div[class^="something"] { } /* target divs */
*[class^="something"] { } /* targets everything */
div[id^="something"] { } /* target divs */
*[id^="something"] { } /* targets everything */
which would work on something like this:-
<div class="something-else-class"></div>
'contains..'
div[class*="something"] { }
which would work on
<div class="is-something-here"></div>
<!-- class name can be anything. "something" can be anywhere -->
'ends with...'
div[class$="something"] { }
which would work on
<div class="you-are-something"></div>
This way you can target all classes and/or id's that have a font-family Rule and change it.
Reference
CSS3 Attribute Selectors: Substring Matching
I'm using Sass to compile my SCSS stylesheets into a single assembled.css to reduce HTTP requests. To namespace individual pages for styling, I wrap each page-specific CSS file in an ID selector for that page's <body> element - for example:
body#support {
.introduction {
#extend %dropcap;
}
}
In nanoc (using ERB), I have a helper that assigns each page's body a dash-separated unique ID based on the HTML folder structure, so the root pages will be #support or #products, while their sub-pages would have an ID like `#products-giantspacelaser'.
I want to make a set of SCSS rules that only apply to these 'products' sub-pages (not including the root-level #products page itself). Is there anything I should look out for regarding specificity if I use an attribute selector instead of an ID for this, as follows?
body[id^="products-"] {
.introduction {
#extend %dropcap;
}
}
I really don't want to use !important, but I do want to ensure that these page-specific rules take precedent over styles set in the '_base.scss' partial that precedes them in the #import order. Seeing as I have full control over the HTML structure, I could also theoretically use Erb in the Sass files to substitute in a comma-separated list of IDs like so:
body#products-giantspacelaser,
body#products-laboratorycamouflage,
body#products-resurrecteddinosaur {
.introduction {
#extend %dropcap;
}
}
- but that seems quite inelegant. Thanks in advance.
EDIT:
I've written my other styles in a really cascade-reliant way:
Normalise CSS
HTML5 Boilerplate's & my own sensible house rules
CSS Libraries (in this case Bourbon & Neat)
A "_source.scss" which in turn imports its own mixins & placeholder selectors.
A "_base.scss" which styles the default layout framework of every page.
A series of .scss files for each page's individual content styling - and, I hoped, overrides of base.scss layout decisions when necessary (if the page needs to take a serious departure from the norm).
Either way, these individual page stylesheets would need to definitely have a higher specificity than earlier defaults, as they were written for a specific purpose & page.
I'm intentionally not using any ID selectors except for this one specific purpose - namespaceing page stylesheets.
Using, say
.services .sharktraining .introduction .disarmingJoke {} --0,0,4,0
in "_base.scss" would surpass
body[id^="products-"] .disarmingJoke {} --0,0,2,1
in a further-down-the-cascade "products.scss", wouldn't it? (N.B. I know needing to use four classes is awful practice, I just don't want to worry about something slipping through the namespace).
I suppose there's another - really dirty - option: to repeat the body[id^="products-"] selector many times, to simply outnumber even the most specific class-strength rule.
It's going to have to depend on how you've written your other styles and whether or not they should take precedence (see: http://coding.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/).
If you match the selector exactly but prefix one of them with your body selector, the prefixed one will be specific enough to take precedence no matter what (even if the order was reversed):
body[id^="products-"] .widget {
color: green;
}
.widget {
color: red;
}
The .widget will be green because the first selector is more specific than the second.
The only problem with using attribute selectors over ids is if you care about IE6. If that's a concern for you, the IE7 JS library by Dean Edwards can help you out: http://code.google.com/p/ie7-js/
If changing how the page information is attached to the body element is an option, my recommendation would be to have the parent directory be an id and the child pages be classes:
<body id="products" class="giantspacelaser" />
This way you can retain the specificity of the id:
// excludes the body#products page, which wouldn't have a class set at all
body[class]#products {
// styling here
}
I've got a question about CSS files and it's order of applying in browser.
We have:
browser (system) CSS file,
user CSS file,
user CSS important file,
site CSS file,
site CSS important file,
When page is loaded some of CSS code replace other code depending on order or !important word. Is order I listed above correct, so site CSS important file can override all previous styling?
CSS code does not replace other CSS code, and the order of parsing style sheets is not relevant. There is really no order of application, since all applicable style sheets are taken into account. When several style sheets assign a value to a property of an element, then the conflict is resolved according to cascade rules. The order is then:
user agent declarations (browser default style)
user normal declarations
author (page) normal declarations
author (page) important declarations
user important declarations
So author (page) !important declarations trump everything but user !important declarations. In Css 1, the order was different, but this was changed in CSS 2 and browsers live by the current rules: the user always has the last word, if he wishes to exercise his rights.
No. User CSS files will be parsed after a site CSS files (otherwise it wouldn't make any sense to have a user CSS file). That doesn't mean it will automatically override everything in a website's css file however, normal CSS specificity rules still apply.
Let's make all paragraphs red for an example my website has the rule:
website.css: p { color: red; }
But if I implement a user style sheet (like userContent.css in FireFox) and say:
FireFox userContent.css: p { color: blue; }
The text color would be blue.
If I then mark the website's rule important:
website.css: p { color: red; !important }
The color would be red again.
Okay that title may not have been too clear, I am building a site for a client that will allow his clients to sell his merchandise. We will call his clients dealers. The dealers want to be able to change the logo and color scheme of the site to match their site. I do not want to go to every single div and table etc. and create a field in the database for it but at the same time I can't let them have full control over the CSS and potentially demolish what their site looks like.
What is the best way to handle this and why?
You can use SASS, http://sass-lang.com/, to achieve this.
custom.scss: - This is what you give to the clients to customize as they want to
/* COLORS */
$backgroundColor: #bada55;
$h1color: #red;
$navigationBackground: #yellow;
$navigationText: #black;
$navigationHover: #red;
$navigationFont: Tahoma;
...etc..
/* WIDGETS */
$arcticleBorderRadius: 5px;
...etc...
/* OTHER CATEGORIES */
In your app.scss import the custom.scss:
#import "custom.scss";
/* YOUR "PRIVATE" CSS RULES /*
body {
background-color: $backgroundColor;
}
aside#nav {
background-color: $navigationBackground;
color: navigationText;
> ul > li:hover {
background-color: $navigationHover;
}
}
/* etc, etc */
You can also use functions to lighten, darken, invert the base colors the customer can overide in custom.scss.
The "workflow" can be:
Customer overrides what they want, and what is available in custom.scss.
You get the custom.scss from the client, compiles a new css, e.g. acme-app.css.
The client calls the site with a request attribute "acme", or a path-variable http://www.myawesomesite.com/acme, in the url that identifies which generated css to load.
After reviewing the options given here and thinking hard about this I have decided that the truly best option for my situation is in fact limiting the items that people are able to change the color of and just store the options in the database. It is more work to begin with but saves on issues in the future
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Avoiding repeated constants in CSS
We have some "theme colors" that are reused in our CSS sheet.
Is there a way to set a variable and then reuse it?
E.g.
.css
OurColor: Blue
H1 {
color:OurColor;
}
There's no requirement that all styles for a selector reside in a single rule, and a single rule can apply to multiple selectors... so flip it around:
/* Theme color: text */
H1, P, TABLE, UL
{ color: blue; }
/* Theme color: emphasis */
B, I, STRONG, EM
{ color: #00006F; }
/* ... */
/* Theme font: header */
H1, H2, H3, H4, H5, H6
{ font-family: Comic Sans MS; }
/* ... */
/* H1-specific styles */
H1
{
font-size: 2em;
margin-bottom: 1em;
}
This way, you avoid repeating styles that are conceptually the same, while also making it clear which parts of the document they affect.
Note the emphasis on "conceptually" in that last sentence... This just came up in the comments, so I'm gonna expand on it a bit, since I've seen people making this same mistake over and over again for years - predating even the existence of CSS: two attributes sharing the same value does not necessarily mean they represent the same concept. The sky may appear red in the evening, and so do tomatoes - but the sky and the tomato are not red for the same reason, and their colors will vary over time independently. By the same token, just because you happen to have two elements in your stylesheet that are given the same color, or size or positioning does not mean they will always share these values. A naive designer who uses grouping (as described here) or a variable processor such as SASS or LESS to avoid value repetition risks making future changes to styling incredibly error-prone; always focus on the contextual meaning of styles when looking to reduce repetition, ignoring their current values.
You can achieve it and much more by using Less CSS.
No, but Sass does this. It's a CSS preprocessor, allowing you to use a lot of shortcuts to reduce the amount of CSS you need to write.
For example:
$blue: #3bbfce;
$margin: 16px;
.content-navigation {
border-color: $blue;
color:
darken($blue, 9%);
}
.border {
padding: $margin / 2;
margin: $margin / 2;
border-color: $blue;
}
Beyond variables, it provides the ability to nest selectors, keeping things logically grouped:
table.hl {
margin: 2em 0;
td.ln {
text-align: right;
}
}
li {
font: {
family: serif;
weight: bold;
size: 1.2em;
}
}
There's more: mixins that act kind of like functions, and the ability to inherit one selector from another. It's very clever and very useful.
If you're coding in Ruby on Rails, it'll even automatically compile it to CSS for you, but there's also a general purpose compiler that can do it for you on-demand.
You're not the first to wonder and the answer is no. Elliotte has a nice rant on it: http://cafe.elharo.com/web/css-repeats-itself/. You could use JSP, or its equivalent, to generate the CSS at runtime.
CSS doesn't offer any such thing. The only solution is to write a preprocessing script that is either run manually to produce static CSS output based on some dynamic pseudo-CSS, or that is hooked up to the web server and preprocesses the CSS prior to sending it to the client.
That's not supported at the moment unless you use some script to produce the CSS based on some variables defined by you.
It seems, though, that at least some people from the browser world are working on it. So, if it really becomes a standard sometime in the future, then we'll have to wait until it is implemented in all the browsers (it will be unusable until then).
Since CSS does not have that (yet, I believe the next version will), follow Konrad Rudolphs advice for preprocesing. You probably want to use one that allready exists: m4
http://www.gnu.org/software/m4/m4.html
You're making it too complicated. This is the reason the cascade exists. Simply provide your element selectors and class your color:
h1 {
color: #000;
}
.a-theme-color {
color: #333;
}
Then apply it to the elements in the HTML, overriding when you need to use your theme colors.
<h1>This is my heading.</h1>
<h1 class="a-theme-color">This is my theme heading.</h1>
I've written a macro (in Visual Studio) that allows me to not only code CSS for named colors but to easily calculate shades or blends of those colors. It also handles fonts. It fires on save and outputs a separate version of the CSS file. This is in line with Bert Bos's argument that any symbol processing in CSS take place at the point of authoring, not not at the point of interpretation.
The full setup along with all the code would be a bit too complicated to post here, but might be appropriate for a blog post down the road. Here's the comment section from the macro which should be enough to get started.
The goals of this approach are as follows:
Allow base colors, fonts, etc. to be defined in a central location, so that an entire pallete or typographical treatment can be easily tweaked without having to use search/replace
Avoid having to map the .CSS extension in IIS
Generate garden-variety text CSS files that can be used, for example, by VisualStudio's design mode
Generate these files once at authoring time, rather than recalculating them every time the CSS file is requested
Generate these files instantly and transparently, without adding extra steps to the tweak-save-test workflow
With this approach, colors, shades of colors, and font families are all represented with shorthand tokens that refer to a list of values in an XML file.
The XML file containing the color and font definitions must be called Constants.xml and must reside in the same folder as the CSS files.
The ProcessCSS method is fired by EnvironmentEvents whenever VisualStudio saves a CSS file. The CSS file is expanded, and the expanded, static version of the file is saved in the /css/static/ folder. (All HTML pages should reference the /css/static/ versions of the CSS files).
The Constants.xml file might look something like this:
<?xml version="1.0" encoding="utf-8" ?>
<cssconstants>
<colors>
<color name="Red" value="BE1E2D" />
<color name="Orange" value="E36F1E" />
...
</colors>
<fonts>
<font name="Text" value="'Segoe UI',Verdana,Arial,Helvetica,Geneva,sans-serif" />
<font name="Serif" value="Georgia,'Times New Roman',Times,serif" />
...
</fonts>
</cssconstants>
In the CSS file, you can then have definitions like:
font-family:[[f:Text]];
background:[[c:Background]];
border-top:1px solid [[c:Red+.5]]; /* 50% white tint of red */
See also Avoiding repeated constants in CSS. As Farinha said, a CSS Variables proposal has been made, but for the time being, you want to use a preprocessor.
You can use mutliple classes in the HTML element's class attribute, each providing part of the styling. So you could define your CSS as:
.ourColor { color: blue; }
.ourBorder { border: 1px solid blue; }
.bigText { font-size: 1.5em; }
and then combine the classes as required:
<h1 class="ourColor">Blue Header</h1>
<div class="ourColor bigText">Some big blue text.</div>
<div class="ourColor ourBorder">Some blue text with blue border.</div>
That allows you to reuse the ourColor class without having to define the colour mulitple times in your CSS. If you change the theme, simply change the rule for ourColour.
This may sound like insanity, but if you are using NAnt (or Ant or some other automated build system), you can use NAnt properties as CSS variables in a hacky way. Start with a CSS template file (maybe styles.css.template or something) containing something like this:
a {
color: ${colors.blue};
}
a:hover {
color: ${colors.blue.light};
}
p {
padding: ${padding.normal};
}
And then add a step to your build that assigns all the property values (I use external buildfiles and <include> them) and uses the <expandproperties> filter to generate the actual CSS:
<property name="colors.blue" value="#0066FF" />
<property name="colors.blue.light" value="#0099FF" />
<property name="padding.normal" value="0.5em" />
<copy file="styles.css.template" tofile="styles.css" overwrite="true">
<filterchain>
<expandproperties/>
</filterchain>
</copy>
The downside, of course, is that you have to run the css generation target before you can check what it looks like in the browser. And it probably would restrict you to generating all your css by hand.
However, you can write NAnt functions to do all sorts of cool things beyond just property expansion (like generating gradient image files dynamically), so for me it's been worth the headaches.
CSS does not (yet) employ variables, which is understandable for its age and it being a declarative language.
Here are two major approaches to achieve more dynamic style handling:
Server-side variables in inline css
Example (using PHP):
<style> .myclass{color:<?php echo $color; ?>;} </style>
DOM manipulation with javascript to change css client-side
Examples (using jQuery library):
$('.myclass').css('color', 'blue');
OR
//The jsvarColor could be set with the original page response javascript
// in the DOM or retrieved on demand (AJAX) based on user action.
$('.myclass').css('color', jsvarColor);