Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 -->  <form>    <p><label for="text_input">Label</label><input type="text" id="text_input" /></p>  </form> </div> 

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?

like image 907
pwaring Avatar asked Aug 06 '12 15:08

pwaring


People also ask

How do I style specific elements in CSS?

The CSS id Selector The id of an element is unique within a page, so the id selector is used to select one unique element! To select an element with a specific id, write a hash (#) character, followed by the id of the element.

Can you apply CSS to a part of HTML document only?

This is not possible. Stylesheets are applied to the whole document and not to subsections of it. Whether an element is affected by the rules is then subject to the used selectors. Following of that, when you want a rule to only apply to elements within <header> , they must begin with header > or header (space) .

How do I apply CSS to all elements except one?

Approach: Use the :not(selector), also known as negation pseudo-class which takes a simple selector as an argument and allows you to style all the elements except the element specified by the selector.


1 Answers

For Bootstrap 3, it's easier if you use less:

Download the Bootstrap source code and make a style.less file like this:

.bootstrap {     @import "/path-to-bootstrap-less.less";     @import "/path-to-bootstrap-responsive-less.less"; } 

Finally, you have to compile the less file; there are many alternatives

https://github.com/cloudhead/less.js/wiki/Command-Line-use-of-LESS https://github.com/cloudhead/less.js/wiki/GUI-compilers-that-use-LESS.js

Or use npm to install less then compile the style.less file to style.css:

npm install -g less lessc style.less style.css 
like image 70
inzurrekt Avatar answered Sep 28 '22 09:09

inzurrekt