In the process of developing using Node.js, sometimes we encounter the problem that the CSS styles in html cannot be displayed properly. This problem usually occurs because we did not introduce the CSS file correctly, or because the default settings of Node.js caused the problem. This article will introduce and analyze this problem and give a solution.
1. Problem Analysis
In Node.js development, we usually use the Express framework to build the server, and use EJS or other template engines to render the page. When rendering a page, we often introduce CSS files through the link tag. The sample code is as follows:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Node.js</title> <link rel="stylesheet" href="styles.css"> </head> <body> <h1>Hello Node.js!</h1> </body> </html>
However, when we open the page in the browser, we find that the CSS file does not seem to be loaded, resulting in The page has no style, as shown in the figure below:
At this time, we need to analyze the cause of the problem.
2. Solution
After analysis, there are usually two reasons for this problem:
In the above example code, when we introduce the CSS file, we use the path relative to the current page, such as styles.css. If we place the file in a directory at the same level as the current page, the path should be correct. However, if we place the file in another directory, the path needs to be modified. For example, if we place the file in a different directory myStyles/ than the current page, the correct path should be: href="myStyles/styles.css"
.
In the default settings of Node.js, the Express framework will use the public folder as a static file directory, and the default settings The .css, .js, .jpg, .png and other file formats are static files. This means that if we want to reference a CSS file in an html file, we need to store the CSS file in the public folder. For example, in the above sample code, our CSS file is stored in the styles/ subdirectory of the public directory. We need to modify the link tag to:
<link rel="stylesheet" href="/styles/styles.css">
In this way, the CSS file can be imported normally .
3. Summary
Through the above introduction and analysis, we can find that when using Node.js for development, it is very important to correctly introduce CSS files. If the introduction is not successful, the page will lack style and affect the user experience. By mastering the correct introduction methods, we can better develop high-quality websites and applications.
The above is the detailed content of HTML does not display css in nodejs. For more information, please follow other related articles on the PHP Chinese website!