处理路径总是有点烦人,你会同意的。幸运的是,使用 Sass 来管理资产并保持代码易于维护非常简单。我们唯一需要的是将基本资产路径存储在一个变量中,以及一些函数来构建我们的 API。
/// Base path for assets (fonts, images...),
/// should not include trailing slash
/// @access public
/// @type String
$asset-base-path: '../assets' !default;
/// Asset URL builder
/// @access private
/// @param {String} $type - Asset type, matching folder name
/// @param {String} $file - Asset file name, including extension
/// @return {URL} - A `url()` function leading to the asset
@function asset($type, $file) {
@return url($asset-base-path + '/' + $type + '/' + $file);
}
/// Image asset helper
/// @access public
/// @param {String} $file - Asset file name, including extension
/// @return {URL} - A `url()` function leading to the image
/// @require {function} asset
@function image($file) {
@return asset('images', $file);
}
/// Font asset helper
/// @access public
/// @param {String} $file - Asset file name, including extension
/// @return {URL} - A `url()` function leading to the font
/// @require {function} asset
@function font($file) {
@return asset('fonts', $file);
}
使用
@font-face {
font-family: 'Unicorn Font';
src: font('unicorn.eot?') format('eot'),
font('unicorn.otf') format('truetype'),
font('unicorn.woff') format('woff'),
font('unicorn.svg#unicorn') format('svg');
font-weight: normal;
font-style: normal;
}
.foo {
background-image: image('kittens.png');
}
@font-face {
font-family: 'Unicorn Font';
src: url("../assets/fonts/unicorn.eot?") format("eot"), url("../assets/fonts/unicorn.otf") format("truetype"), url("../assets/fonts/unicorn.woff") format("woff"), url("../assets/fonts/unicorn.svg#unicorn") format("svg");
font-weight: normal;
font-style: normal;
}
.foo {
background-image: url("../assets/images/kittens.png");
}
太方便了!我一直对 CSS 预处理器持怀疑态度,但两周前我开始使用“Sass”,天啊,太值了!顺便说一句,你的代码片段帮助很大,谢谢!
你好,
CSS Tricks(一万次感谢你)。
但请帮助我理解;在了解上面示例使用示例路径后。
如果我使用 SASS、SCSS、Compass、Bourbons、Neat 等构建了一个网站。
当我将网站投入生产时,是否应该只使用我创建的压缩 style.css 文件来删除所有上述工具包?
也就是说,我认为这样做的一个好方法是删除 /assets 目录。
这种想法“可以”吗?
Charles。
简单点。在 SASS/SCSS 中只需编写变量
$assetPath : "images/img";
background: url(#{$assetPath}/pk-bg.jpg) no-repeat center top;
这样绝对可以!