pwaring pwaring - 1 year ago 87
CSS Question

Applying CSS styles only to certain elements

I have an existing website with lots of old pages and forms laid out with tables which I am trying to gradually transition to CSS. I want to use the Twitter Bootstrap stylesheets - particularly the styles for forms - but only on sections of pages where I have explicitly requested them. For example, I might surround the whole form in a div like so:

<div class="bootstrap">
<!-- everything in here should have the Bootstrap CSS applied -->
<p><label for="text_input">Label</label><input type="text" id="text_input" /></p>

I want all other forms to remain the same as they are now, because I won't be able to change them all at the same time. Is there a simple way to do this? I could go through every single style in the Bootstrap CSS and add a parent selector (e.g. 'p' would become 'div.bootstrap p'), but that would take a long time and it would be easy to miss styles.

Edit: If such a thing isn't possible, is there a free tool which can extract all the styles from a file, add a prefix and then save them back again?

Answer Source

The final fix was to use SASS (recommended by someone off-site), as that allows you to nest elements and then automatically produce the final CSS. Step by step the process is:

  1. Concatenate the two Bootstrap files (bootstrap.css and bootstrap-responsive.css) into bootstrap-all.css.
  2. Create a new SASS file, bootstrap-all.scss, with the content div.bootstrap {.
  3. Append bootstrap-all.css to bootstrap-all.scss.
  4. Close the div.bootstrap selector by appending } to bootstrap-all.scss.
  5. Run SASS on bootstrap-all.scss to produce a final CSS file.
  6. Run YUI Compressor on the final file to produce a minimised version.
  7. Add minimised version to head element and wrap everything I want the styles to apply to in <div class="bootstrap"></div>.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download