仅将 CSS 样式应用于某些元素 [英] Applying CSS styles only to certain elements
问题描述
我有一个现有的网站,其中有很多旧页面和表格,我正在尝试逐渐过渡到 CSS.我想使用 Twitter Bootstrap 样式表——尤其是表单的样式——但只在我明确要求它们的页面部分上使用.例如,我可能会像这样将整个表单包围在一个 div 中:
<!-- 这里的所有内容都应该应用 Bootstrap CSS --><表格><p><label for="text_input">Label</label><input type="text" id="text_input"/></p></表单>
我希望所有其他表格都保持现在的样子,因为我无法同时更改它们.有没有一种简单的方法可以做到这一点?我可以检查 Bootstrap CSS 中的每一个样式并添加一个父选择器(例如,'p' 会变成 'div.bootstrap p'),但这需要很长时间,而且很容易错过样式.
如果这样的事情是不可能的,是否有免费的工具可以从文件中提取所有样式,添加前缀然后再次保存它们?
最后的修复是使用 SASS (由非现场人员推荐),因为这允许您嵌套元素,然后自动生成最终的 CSS.分步过程是:
- 将两个 Bootstrap 文件(
bootstrap.css
和bootstrap-responsive.css
)连接到bootstrap-all.css
. - 创建一个新的 SASS 文件,
bootstrap-all.scss
,内容为div.bootstrap {
. - 将
bootstrap-all.css
附加到bootstrap-all.scss
. - 通过将
}
附加到bootstrap-all.scss
来关闭div.bootstrap
选择器. - 在
bootstrap-all.scss
上运行 SASS 以生成最终的 CSS 文件. - 对最终文件运行 YUI Compressor 以生成最小化版本.
- 将最小化版本添加到 head 元素并将我希望样式应用到的所有内容包装在
<div class="bootstrap"></div>
中.
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?
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:
- Concatenate the two Bootstrap files (
bootstrap.css
andbootstrap-responsive.css
) intobootstrap-all.css
. - Create a new SASS file,
bootstrap-all.scss
, with the contentdiv.bootstrap {
. - Append
bootstrap-all.css
tobootstrap-all.scss
. - Close the
div.bootstrap
selector by appending}
tobootstrap-all.scss
. - Run SASS on
bootstrap-all.scss
to produce a final CSS file. - Run YUI Compressor on the final file to produce a minimised version.
- Add minimised version to head element and wrap everything I want the styles to apply to in
<div class="bootstrap"></div>
.
这篇关于仅将 CSS 样式应用于某些元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!