仅将 CSS 样式应用于某些元素 [英] Applying CSS styles only to certain elements

查看:35
本文介绍了仅将 CSS 样式应用于某些元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个现有的网站,其中有很多旧页面和表格,我正在尝试逐渐过渡到 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.分步过程是:

  1. 将两个 Bootstrap 文件(bootstrap.cssbootstrap-responsive.css)连接到 bootstrap-all.css.
  2. 创建一个新的 SASS 文件,bootstrap-all.scss,内容为 div.bootstrap {.
  3. bootstrap-all.css 附加到 bootstrap-all.scss.
  4. 通过将 } 附加到 bootstrap-all.scss 来关闭 div.bootstrap 选择器.
  5. bootstrap-all.scss 上运行 SASS 以生成最终的 CSS 文件.
  6. 对最终文件运行 YUI Compressor 以生成最小化版本.
  7. 将最小化版本添加到 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:

  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>.

这篇关于仅将 CSS 样式应用于某些元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆