ESP32-Web-Server编程-CSS 基础 2

ESP32-Web-Server编程-CSS 基础 2

概述

如上节所述,可以使用外部 CSS 文件来修饰指定的 HTML 文件。

  • 外部引用 - 使用外部 CSS 文件

    当样式需要被应用到很多页面的时候,外部样式表将是理想的选择。使用外部样式表,就可以通过更改一个文件来改变所有包含该 CSS 文件的 HTML 的外观。在 HTML 文件中使用 href=XXX,来导入对应的 CSS 文件到该文件。就像 C 语言的头文件、或者 python 语言的 import 一样。

    
    
    
    

网页内容不复杂时,可以使用内联样式,网页内容复杂的话,最好的方式是通过外部引用CSS文件。

需求及功能解析

与上节 的后台代码类似,本节主要演示如何使用外部 CSS 文件,来让读者了解并体会其基本语法与作用。

如果你是第一次学习该系列的博客,请参考 A 博客来熟悉编程使用的方法。

示例解析

目录结构

├── CMakeLists.txt
├── main
│   ├── CMakeLists.txt
│   └── main.c                 User application
├── components
│   └── fs_image
		└── index.html
		└── css
			└── stylesheet.css
|	└── url_handlers
		└── url_handlers.c
		└── ...
└── README.md                  This is the file you are currently reading
  • 目录结构主要包含主目录 main,以及组件目录 components. 与前述章节不同的是,在 components/fs_image/css 目录定义了一个 stylesheet.css 文件。该css 文件定义了一些样式类别:
.box { 
    background-color: rgb(66, 138, 148);
  }
  
  .mygrid { 
    max-width: 800px; 
    margin: 0 auto; 
    display: grid; 
    grid-gap: 2rem; 
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  }
  
  html {
    font-family: Arial, Helvetica, sans-serif; 
    display: inline-block; 
    text-align: center;
  }
  
  p {
    font-size: 16px;
  }

然后在 components/fs_image/index.html 中通过外部引用关键字 link 引入该 css 文件,如此该 css 文件可以作用于该 HTML 中的元素:


    IOT LAO WANG
    
    
  

读者可以删除或在屏蔽 这行代码,对比包含该代码和去掉该部分代码后的异同,增加对这部分内容的理解。

最后在后端代码中为了让浏览器加载到 这行代码时客户端浏览器能能正确从 web 服务器接收到对应的 css 文件,因此在 url_handlers/url_handlers.c 中增加对应的 handler 函数css_get_handler()

/* Handler to respond with CSS.
 * Browsers expect to GET website icon at URI /stylesheet.css.*/
static esp_err_t css_get_handler(httpd_req_t *req)
{
    extern const unsigned char css_start[] asm("_binary_stylesheet_css_start");
    extern const unsigned char css_end[]   asm("_binary_stylesheet_css_end");
    const size_t css_size = (css_end - css_start);
    httpd_resp_set_type(req, "text/css");
    httpd_resp_send(req, (const char *)css_start, css_size);
    return ESP_OK;
}

httpd_uri_t httpd_uri_array[URL_HANDLERS_MAX] = {
    {"/", HTTP_GET, index_html_get_handler, NULL},
    {"/favicon.ico", HTTP_GET, favicon_get_handler, NULL},
    {"/stylesheet.css", HTTP_GET, css_get_handler, NULL}, // 浏览器请求时通过该函数发送 CSS 文件
};

示例输出:

ESP32-Web-Server编程-CSS 基础 2_第1张图片

讨论

读者朋友可以自己更改 CSS 文件中的一些属性的值来查看对网页的外观的影响。

总结

1)本节主要演示如何使用外部 CSS 文件,在前端代码 html 中通过 link 标签引用指定的 CSS 文件,然后在后端代码中通过增加发送 CSS 文件的 handler 就可以正确应用外部的 CSS 文件。

资源链接

1)ESP32-Web-Server ESP-IDF系列博客介绍
2)对应示例的 code 链接 (点击直达代码仓库)

3)下一篇:ESP32-Web-Server编程-JS 基础 1

(码字不易感谢点赞或收藏)

你可能感兴趣的:(ESP-Web开发,ESP,前端,css,物联网,web,服务器)