【问题标题】:Why is my stylesheet applying to all my ejs files?为什么我的样式表适用于我的所有 ejs 文件?
【发布时间】:2019-05-03 18:56:23
【问题描述】:

我正在使用 Express、MongoDB 和 EJS 模板视图引擎创建一个 nodeJS 应用程序。我已经创建了创建服务器的 server.js 文件。我创建了一个单独的 header.ejs 文件,我将把它包含在我的其他 ejs 文件中(如 index.ejs、about.ejs、contact..ejs 等)。但是,当我仅为 header.ejs 文件创建样式表时,样式将应用于所有 ejs 文件(index.ejs、about.ejs 等) 我已将 header.ejs 文件放在 ./public/partials/ 文件夹中,样式表位于 ./public/assets/ 文件夹中,我的 index.ejs 文件位于 ./views/ 文件夹中。

我在 server.js 文件中使用了 app.use(express.static(__dirname + "/public")),在 index.ejs 中使用了 /assets/style.css,在 header.ejs 中使用了 /assets/header.css文件。

服务器.js

app.set('view engine' ,  'ejs');
app.use(express.static(__dirname + "/public"));
app.use(employeeController);

employeeController.js

router.get('/employee' , function(req, res){
    res.render("index");
});

module.exports = 路由器;

header.ejs

<link rel="stylesheet" href="assets/header.css">
<h2>Company Logo</h2>

index.ejs

 <link rel="stylesheet" href="/assets/style.css">
 <% include ../public/partials/header.ejs %>
  <h2>Please Enter the New Employee Information</h2>

当我将 h2 {color: indianred;} 放入 header.css 文件时,即使 header.css 仅链接到 header.ejs,index.ejs 文件中的颜色也会发生变化。

我只想更改 header.ejs 的。 我该怎么做?

【问题讨论】:

    标签: html css node.js express ejs


    【解决方案1】:

    当您将header.ejs 包含到index.ejs 中时,css 也会被添加。这就是您遇到此问题的原因。

    要解决此问题,请将class/id 添加到h2

    <h2 class="h2_css">Company Logo</h2>
    

    或者,

    <h2 id="h2_css">Company Logo</h2>
    

    现在像这样添加你的css

    h2.h2_css {color: indianred;} 
    

    h2#h2_css {color: indianred;} 
    

    【讨论】:

    • 是的,我想添加类和 id,但我想如果没有这些我可以做到这一点,因为它会更好,因为我的页眉和页脚 ejs 文件的内容不会有太多所以我不想使用类或id。不过非常感谢您的建议。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-01
    • 1970-01-01
    相关资源
    最近更新 更多