Der Umgang mit Pfaden ist immer etwas mühsam, das wirst du zugeben. Glücklicherweise ist es mit Sass extrem einfach, eine schöne API zur Verwaltung von Assets zu haben und den Code wartungsfreundlich zu halten. Alles, was wir brauchen, ist, den Basis-Asset-Pfad in einer Variablen zu speichern und ein paar Funktionen zu haben, um unsere API zu erstellen.
/// 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);
}
Verwendung
@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");
}
Das ist so praktisch! Ich war immer skeptisch gegenüber CSS-Präprozessoren, aber vor zwei Wochen habe ich angefangen, "sassy" zu sein, und Mann, es lohnt sich! Übrigens, deine Snippets helfen sehr, danke!
Hallo,
Deine CSS Tricks (tausend Dank).
Aber bitte hilf mir zu verstehen; nachdem ich verstanden habe, dass das obige Beispiel Beispielpfade verwendet.
Wenn ich eine Website mit SASS, SCSS, Compass, Bourbons, Neat usw. erstellt habe.
Wenn ich die Website in Produktion nehme, sollte ich dann nicht alle oben genannten Kits entfernen und nur meine erstellte minimierte style.css verwenden.
Ich meine, ich hätte gedacht, ein cooler Weg, dies zu tun, wäre dann, das /assets-Verzeichnis zu entfernen.
Ist dieses Denken "okay"?
Charles.
Sei einfach. in SASS/SCSS schreibe einfach eine Variable
$assetPath : "images/img";background: url(#{$assetPath}/pk-bg.jpg) no-repeat center top;Das wird zu 100 % funktionieren!