Magento 2 通过 layout 文件引入 CSS。从技术讲,使用模板文件也可以引入 CSS,但是我们强烈推荐不要这样做。
CSS 的类名可以用在 templates 和 layouts 中
本篇描述 Magento 应用文件系统中默认情况下 CSS 文件是如何组织的,以及在布局中引入 CSS 的推荐做法。
Magento 的 CSS 是如何组织的
按照惯例来讲, CSS 和 LESS 文件只存在 theme 中。Module 文件夹中不包含任何样式。
在 theme 文件夹中,样式表被存放在如下位置:
Directory, relative to
Description
/_/web/css
特定模块的样式
/web/css
包含以下文件:
print.less: used to generate styles for the printed version of store pages.
_styles.less – a composite file, which includes all LESS files used in the theme. The underscore sign (_) in a file name conventionally means that a file is not used independently, but is included in other files.
styles-m.less: used to generate mobile-specific styles, includes _styles.less
styles-l.less: used to generate desktop-specific styles, includes _styles.less.
/source: this subdirectory contains LESS configuration files that invoke mixins from the Magento UI library.
/source/_theme.less: overrides the default Magento UI library variables values.
通过布局引入 CSS
通常来讲,你引入的 CSS ,所有的店铺页都是可以访问的。Magento_Theme的default_head_blocks.xml定义了所有 Magento 页面的
部分。推荐做法是在你自己的theme 中增加一个default_head_blocks.xml来扩展它。你 theme 中的default_head_blocks.xml应该放置在类似下面的位置/Magento_Theme/layout/default_head_blocks.xml。要引入某个 css 文件,在部分添加这样的代码:
是相对于你主题文件目录的(/web)。下面是 Blank 主题引入 css 的例子:
#File: /Magento_Theme/layout/default_head_blocks.xml
如果系统没有找到css 文件,就会找同名的.less文件。这是Magento 内置的机制,可以参考 CSS Preprocessing 获得更多信息
参考文档