整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:

「asp.net core 系列」教你如何引用静态资源和布局页的使用

. 前言

在之前的4篇的内容里,我们较为详细的介绍了路由以及控制器还有视图之间的关系。也就是说,系统如何从用户的HTTP请求解析到控制器里,然后在控制器里处理数据,并返回给视图,在视图中显示出来。这一篇我将为大家介绍基础的最后一部分,布局页和静态资源引入。



1. 布局页

在控制器和视图那一篇,我们了解到_ViewStart 里设置了一个Layout属性的值,这个值正是用来设置布局页的。所谓的布局页,就是视图的公用代码。在实际开发中,布局页通常存放我们为整个系统定义的页面框架,视图里写每个视图的页面。

回顾一下,默认的_ViewStart里的内容是:

@{
    Layout = "_Layout";
}

默认的布局页指定的是名为_Layout的布局页,在本系列第三篇中,我们得知这个视图应当在Shared文件夹下,那我们进去看一下这个视图有什么内容:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - MvcWeb</title>
    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="~/css/site.css" />
</head>
<body>
    <header>
        <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
            <div class="container">
                <a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">MvcWeb</a>
                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
                        aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse">
                    <ul class="navbar-nav flex-grow-1">
                        <li class="nav-item">
                            <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
                        </li>
                    </ul>
                </div>
            </div>
        </nav>
    </header>
    <div class="container">
        <main role="main" class="pb-3">
            @RenderBody()
        </main>
    </div>

    <footer class="border-top footer text-muted">
        <div class="container">
            © 2020 - MvcWeb - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
        </div>
    </footer>
    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
    <script src="~/js/site.js" asp-append-version="true"></script>
    @RenderSection("Scripts", required: false)
</body>
</html>

这是默认的布局页内容,看着挺多的,但是除了一些html代码,里面还有一些关键的地方需要注意。



1.1 RenderSection

RenderSection 分部渲染,在页面中创建一个标记,表示这个页面块将在子视图(或者是路由的实际渲染视图)中添加内容。

来,我们看一下微软官方给的注释:

In layout pages, renders the content of the section named name.

意思就是在布局页中,渲染名称为name的分部内容。

新创建一个分布页,名称为_Layout1:

<html>
    <head>
        <title>Render 测试</title>
    </head>
    <body>
        @RenderSection("SectionDemo")
    </body>
</html>

这个布局页里什么都没有,只有一个RenderSection。现在我们新建一个控制器:

using Microsoft.AspNetCore.Mvc;

namespace MvcWeb.Controllers
{
    public class RenderTestController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }
}

创建对应的视图:

Views / RenderTest/Index.cshtml

先设置布局页为_Layout1:

@{
    Layout = "_Layout1";
}

先试试启动应用,访问:

http://localhost:5006/RenderTest/Index

正常情况下,你应该能看到这个页面:

仔细看一下信息,意思是在 RenderTest/Index.cshtml 视图中没有找到 SectionDemo 的分部内容。

那么,如何在视图中设置分部内容呢?

@{
    Layout = "_Layout1";
}
@section SectionDemo{
    <h1>你好</h1>

}

使用 @section <Section 名称> 后面跟一对大括号,在大括号中间的内容就是这个section(分部)的内容。

重启应用,然后刷新页面,你能看到这样的页面:

如果不做特殊要求的话,定义在布局页中的分部块,视图必须实现。当然,RenderSection还有一个参数,可以用来设置分部不是必须的:

public HtmlString RenderSection(string name, bool required);

1.2 RenderBody

先看下微软给的官方注释:

In a Razor layout page, renders the portion of a content page that is not within a named section.

简单讲,如果在布局页中设置了@RenderBody,那么在使用了这个布局页的视图里所有没被分部块包裹的代码都会渲染到布局页中声明了@RenderBody的地方。

修改_Layout1.cshtml:

<html>
    <head>
        <title>Render 测试</title>
    </head>
    <body>
        <h1>RenderBody 测试 -之前</h1>
        @RenderBody()
        <h1>RenderBody 测试 -之后</h1>
    </body>
</html>

修改RenderTest/Index.cshtml:

@{
    Layout = "_Layout1";
}

RenderBody测试
<h1>我是视图的内容!</h1>

重启应用,刷新刚刚访问的页面:

可以看出,RenderBody渲染的位置。

2. 静态资源引入

通常情况下,静态资源的引入与HTML引用js和css等资源是一致的,但是对于我们在编写系统时自己创建的脚本和样式表,asp.net core提供了不同的处理方式。那就是服务器端压缩功能。

asp.net core 3.0 的mvc 默认项目是不启动这个功能的,需要我们额外的开启支持。



2.1 开启支持

先引入 BuildBundleMinifier

cd MvcWeb # 切换目录到MvcWeb项目下
dotnet add package BuildBundleMinifier

创建 bundleconfig.json

[
    {
        "outputFileName": "wwwroot/css/site.min.css",
        "inputFiles": [
            "wwwroot/css/site.css"
        ]
    },
      {
        "outputFileName": "wwwroot/js/site.min.js",
        "inputFiles": [
          "wwwroot/js/site.js"
        ],
        "minify": {
          "enabled": true,
          "renameLocals": true
        },
        "sourceMap": false
      }
]

每个节点允许设置项:

  • outputFileName 生成的捆绑压缩文件,通常路径携带wwwroot
  • inputFiles 数组,包含要压缩到此次输出文件的文件路径,会按照添加的顺序依次加入
  • minify 输出类型的缩小选项,可选。 默认是 enabled: true
  • sourceMap 表示是否为捆绑的文件生成源映射的标记
  • sourceMapRootPath 源映射文件的路径

2.2 使用

正常情况下在布局页中,把压缩后的文件路径引入即可。不过在开发中,通常按照以下方式引用:

<environment exclude="Development">
    <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
</environment>
<environment include="Development">
    <link rel="stylesheet" href="~/css/site.css" />
</environment>

注: asp-append-version 表示在引用路径追加一个版本号,这是针对html静态资源缓存的问题的一个解决方案,这一步是由程序决定的。

environment表示环境,现在大家知道这个写法就行,在接下来的篇幅会讲。

3. 静态资源目录

我们知道到目前为止,我们的静态资源都是在wwwroot目录下。那么我们是否可以修改或者添加别的目录作为静态资源目录呢?

在Startup.cs文件内的Configure方法下有这样一行代码:

app.UseStaticFiles();

这行代码的意思就是启用静态文件,程序自动从 wwwroot寻找资源。那么,我们就可以从这个方法入手,设置我们自己的静态资源:

public static IApplicationBuilder UseStaticFiles(this IApplicationBuilder app, StaticFileOptions options);

我们找到了这个方法的另一个重载版本,里面有一个参数类:

public class StaticFileOptions : SharedOptionsBase
{
    public StaticFileOptions();
    public StaticFileOptions(SharedOptions sharedOptions);
    public IContentTypeProvider ContentTypeProvider { get; set; }
    public string DefaultContentType { get; set; }
    public HttpsCompressionMode HttpsCompression { get; set; }
    public Action<StaticFileResponseContext> OnPrepareResponse { get; set; }
    public bool ServeUnknownFileTypes { get; set; }
}

并没有发现我们想要的,先别慌,它还有个父类。我们再去它的父类里看看:

public abstract class SharedOptionsBase
{
    protected SharedOptionsBase(SharedOptions sharedOptions);
    public IFileProvider FileProvider { get; set; }
    public PathString RequestPath { get; set; }
    protected SharedOptions SharedOptions { get; }
}

这下就比较明了了,需要我们提供一个文件提供器,那么我们来找一个合适的IFileProvider实现类吧:

public class PhysicalFileProvider : IFileProvider, IDisposable

这个类可以满足我们的要求,它位于命名空间:

namespace Microsoft.Extensions.FileProviders

那么,添加一组我们自己的配置吧:

using Microsoft.Extensions.FileProviders;

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // 省略其他代码,仅添加以下代码
    app.UseStaticFiles(new StaticFileOptions
    {
        FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(),"OtherStatic")),
    });
}

在项目的根目录创建名为OtherStatic的文件夹,然后在里面创建个文件夹,例如: files,并在这个文件夹里随便添加一个文件。

然后启动应用访问:

http://localhost:5006/files/<你添加的文件(包括后缀名)>

然后能在浏览器中看到这个文件被正确响应。

当然,这里存在一个问题,如果在 OtherStatic中的文件在wwwroot也有相同目录结构的文件存在,这样访问就会出现问题。这时候,可以为我们新加的这个配置设置一个请求前缀:

app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(),"OtherStatic")),
    RequestPath = "/other"
});

重启程序,然后访问:

http://localhost:5006/other/files/<你添加的文件(包括后缀名)>

然后就能看到刚才响应的文件,重新访问之前的路径,发现浏览器提示404。



4. 总结

在这一篇,我们讲解了布局页的内容,静态资源的压缩绑定以及添加一个新的静态资源目录。通过这几篇内容,让我们对asp.net core mvc有了一个基本的认知。下一篇,我们将重新创建一个项目,并结合之前的内容,以实战为背景,带领大家完成一个功能完备的web系统。

求关注,求点赞,求转发~~有啥可以评论哟

  1. 建一个 index.htmlindex.css 文件并根据提供内容进行初始化。
  2. index.html 中的 <style> 标签下,找到 ”补全代码 1“ 和 ”补全代码 2“,根据测试验证中的效果图,进行媒体查询与 CSS 代码补充。

按以上要求完成以下效果:

(1)初次加载显示效果如下:

(2)改变窗口大小,当宽度小于 959px 时,页面效果如下:

(3)改变窗口大小,当宽度小于 720px 时,页面效果如下:

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>改版前</title>
    <link rel="stylesheet" type="text/css" href="index.css" />
    <style>
      /*补全代码1*/
      /* @media ... { */
        @media screen and (max-width:959px){

        }
      .responsive menu {
        clear: left;
        float: left;
        width: 17.5%;
      }
      .responsive article {
        clear: none;
        float: left;
        margin: 20px 0;
        width: 64.9%;
      }
      .responsive article #article_inner {
        margin: 0 20px;
      }
      .responsive aside {
        clear: none;
        float: right;
        width: 17.5%;
      }
      /*}*/

      /*补全代码2
        @media .... {
            CSS Code
        }
        */
        @media screen and (max-width:720px){
            
        }
    </style>
  </head>

  <body class="responsive">
    <div id="page_wrapper">
      <header>
        <div id="header_inner">
          <h1 id="header_responsive">Static Page</h1>
        </div>
      </header>

      <div id="content_wrapper">
        <menu>
          <div id="menu_inner">
            <ul class="menu_1">
              <li class="menu_1">
                <a
                  href="#nogo"
                  class="menu_1"
                  title="Dummy placeholder link. This doesn't go anywhere."
                  >Menu 1</a
                >
                <ul class="menu_2">
                  <li class="menu_2">
                    <a
                      href="#nogo"
                      class="menu_2"
                      title="Dummy placeholder link. This doesn't go anywhere."
                      >Menu 1 a</a
                    >
                  </li>
                  <li class="menu_2">
                    <a
                      href="#nogo"
                      class="menu_2"
                      title="Dummy placeholder link. This doesn't go anywhere."
                      >Menu 1 b</a
                    >
                  </li>
                  <li class="menu_2">
                    <a
                      href="#nogo"
                      class="menu_2"
                      title="Dummy placeholder link. This doesn't go anywhere."
                      >Menu 1 c</a
                    >
                  </li>
                </ul>
              </li>
              <li class="menu_1">
                <a
                  href="#nogo"
                  class="menu_1"
                  title="Dummy placeholder link. This doesn't go anywhere."
                  >Menu 2</a
                >
                <ul class="menu_2">
                  <li class="menu_2">
                    <a
                      href="#nogo"
                      class="menu_2"
                      title="Dummy placeholder link. This doesn't go anywhere."
                      >Menu 2 a</a
                    >
                  </li>
                  <li class="menu_2">
                    <a
                      href="#nogo"
                      class="menu_2"
                      title="Dummy placeholder link. This doesn't go anywhere."
                      >Menu 2 b</a
                    >
                  </li>
                  <li class="menu_2">
                    <a
                      href="#nogo"
                      class="menu_2"
                      title="Dummy placeholder link. This doesn't go anywhere."
                      >Menu 2 c</a
                    >
                  </li>
                </ul>
              </li>
              <li class="menu_1">
                <a
                  href="#nogo"
                  class="menu_1"
                  title="Dummy placeholder link. This doesn't go anywhere."
                  >Menu 3</a
                >
                <ul class="menu_2">
                  <li class="menu_2">
                    <a
                      href="#nogo"
                      class="menu_2"
                      title="Dummy placeholder link. This doesn't go anywhere."
                      >Menu 3 a</a
                    >
                  </li>
                  <li class="menu_2">
                    <a
                      href="#nogo"
                      class="menu_2"
                      title="Dummy placeholder link. This doesn't go anywhere."
                      >Menu 3 b</a
                    >
                  </li>
                  <li class="menu_2">
                    <a
                      href="#nogo"
                      class="menu_2"
                      title="Dummy placeholder link. This doesn't go anywhere."
                      >Menu 3 c</a
                    >
                  </li>
                </ul>
              </li>
            </ul>
          </div>
        </menu>

        <div id="article_aside_wrapper">
          <article>
            <div id="article_inner">
              <div id="intro">
                <h1>How To Use</h1>

                <p>
                  Ever wondered what the difference between Adaptive,
                  Responsive, Static and Liquid sites is? Had someone try and
                  explain it only to be left more confused?
                </p>

                <p>
                  Pick a flavor from the drop down on the top of the page then
                  drag your window narrower and wider, taller and shorter. It
                  will make much more sense when you see for yourself how the
                  approach works.
                </p>
              </div>

              <div id="overview">
                <img
                  src="https://labfile.oss.aliyuncs.com/courses/3944/layout.png "
                  alt="Single Column Layout"
                  id="layout_1"
                />
                <img
                  src="https://labfile.oss.aliyuncs.com/courses/3944/layout.png "
                  alt="Two Column Layout"
                  id="layout_2"
                />

                <h1 class="overview_adaptive">Adaptive</h1>

                <p class="overview_adaptive">
                  Adaptive is characterized by having defined layouts for
                  different resolutions. Within each layout, resizing the window
                  does not change the layout.
                </p>

                <p class="overview_adaptive">
                  You can think of Adaptive as a series of
                  <a
                    href="#nogo"
                    class="mode"
                    rel="static"
                    title="Change to Static"
                    >Static</a
                  >
                  layouts.
                </p>

                <h1 class="overview_liquid">Liquid</h1>

                <p class="overview_liquid">
                  Liquid (also called "Fluid") is characterized by scaling the
                  width of parts of the design relative to the window. It tends
                  to fail when the window is much smaller or much larger than it
                  was originally designed for.
                </p>

                <h1 class="overview_responsive">Responsive</h1>

                <p class="overview_responsive">
                  Responsive is characterized by having defined layouts for
                  different resolutions. Within each layout, the design is
                  liquid and resizes the width of elements relative to the
                  changing window size.
                </p>

                <p class="overview_responsive">
                  You can think of Responsive as a series of
                  <a
                    href="#nogo"
                    class="mode"
                    rel="liquid"
                    title="Change to Liquid"
                    >Liquid</a
                  >
                  layouts.
                </p>

                <h1 class="overview_static">Static</h1>

                <p class="overview_static">
                  Static layouts are the traditional web: one design that sits
                  in the center of the page and requires horizontal scrolling if
                  the window is too small for it. M dot sites are the
                  traditional answer to this, providing a wholly separate site
                  for a lower resolution - and all the work of creating a
                  separate site.
                </p>
              </div>

              <!-- Start: Single Block -->
              <div class="block">
                <div class="block_inner">
                  <img
                    src="https://labfile.oss.aliyuncs.com/courses/3944/layout.png "
                  />
                  <div class="block_content">
                    <h3>Title</h3>
                    <p class="meta">Month dd, yyyy</p>
                    <p class="summary">
                      Summary summary summary summary summary summary
                    </p>
                    <p class="main">
                      Content content content content content content content
                      content content content content content content content
                      content content
                    </p>
                    <a
                      href="#nogo"
                      title="Dummy placeholder link. This doesn't go anywhere."
                      >Link</a
                    >
                  </div>
                </div>
              </div>
              <!-- End: Single Block -->

              <!-- Start: Single Block -->
              <div class="block">
                <div class="block_inner">
                  <img
                    src="https://labfile.oss.aliyuncs.com/courses/3944/layout.png "
                  />
                  <div class="block_content">
                    <h3>Title</h3>
                    <p class="meta">Month dd, yyyy</p>
                    <p class="summary">
                      Summary summary summary summary summary summary
                    </p>
                    <p class="main">
                      Content content content content content content content
                      content content content content content content content
                      content content
                    </p>
                    <a
                      href="#nogo"
                      title="Dummy placeholder link. This doesn't go anywhere."
                      >Link</a
                    >
                  </div>
                </div>
              </div>
              <!-- End: Single Block -->

              <!-- Start: Single Block -->
              <div class="block">
                <div class="block_inner">
                  <img
                    src="https://labfile.oss.aliyuncs.com/courses/3944/layout.png "
                  />
                  <div class="block_content">
                    <h3>Title</h3>
                    <p class="meta">Month dd, yyyy</p>
                    <p class="summary">
                      Summary summary summary summary summary summary
                    </p>
                    <p class="main">
                      Content content content content content content content
                      content content content content content content content
                      content content
                    </p>
                    <a
                      href="#nogo"
                      title="Dummy placeholder link. This doesn't go anywhere."
                      >Link</a
                    >
                  </div>
                </div>
              </div>
              <!-- End: Single Block -->

              <!-- Start: Single Block -->
              <div class="block">
                <div class="block_inner">
                  <img
                    src="https://labfile.oss.aliyuncs.com/courses/3944/layout.png "
                  />
                  <div class="block_content">
                    <h3>Title</h3>
                    <p class="meta">Month dd, yyyy</p>
                    <p class="summary">
                      Summary summary summary summary summary summary
                    </p>
                    <p class="main">
                      Content content content content content content content
                      content content content content content content content
                      content content
                    </p>
                    <a
                      href="#nogo"
                      title="Dummy placeholder link. This doesn't go anywhere."
                      >Link</a
                    >
                  </div>
                </div>
              </div>
              <!-- End: Single Block -->

              <!-- Start: Single Block -->
              <div class="block">
                <div class="block_inner">
                  <img
                    src="https://labfile.oss.aliyuncs.com/courses/3944/layout.png "
                  />
                  <div class="block_content">
                    <h3>Title</h3>
                    <p class="meta">Month dd, yyyy</p>
                    <p class="summary">
                      Summary summary summary summary summary summary
                    </p>
                    <p class="main">
                      Content content content content content content content
                      content content content content content content content
                      content content
                    </p>
                    <a
                      href="#nogo"
                      title="Dummy placeholder link. This doesn't go anywhere."
                      >Link</a
                    >
                  </div>
                </div>
              </div>
              <!-- End: Single Block -->
            </div>
          </article>

          <aside>
            <div id="aside_inner">
              <!-- Start: Single Block -->
              <div class="block">
                <div class="block_inner">
                  <img
                    src="https://labfile.oss.aliyuncs.com/courses/3944/layout.png "
                  />
                  <div class="block_content">
                    <h3>Title</h3>
                    <p class="meta">Month dd, yyyy</p>
                    <p class="summary">
                      Summary summary summary summary summary summary
                    </p>
                    <p class="main">
                      Content content content content content content content
                      content content content content content content content
                      content content
                    </p>
                    <a
                      href="#nogo"
                      title="Dummy placeholder link. This doesn't go anywhere."
                      >Link</a
                    >
                  </div>
                </div>
              </div>
              <!-- End: Single Block -->

              <!-- Start: Single Block -->
              <div class="block">
                <div class="block_inner">
                  <img
                    src="https://labfile.oss.aliyuncs.com/courses/3944/layout.png "
                  />
                  <div class="block_content">
                    <h3>Title</h3>
                    <p class="meta">Month dd, yyyy</p>
                    <p class="summary">
                      Summary summary summary summary summary summary
                    </p>
                    <p class="main">
                      Content content content content content content content
                      content content content content content content content
                      content content
                    </p>
                    <a
                      href="#nogo"
                      title="Dummy placeholder link. This doesn't go anywhere."
                      >Link</a
                    >
                  </div>
                </div>
              </div>
              <!-- End: Single Block -->

              <!-- Start: Single Block -->
              <div class="block">
                <div class="block_inner">
                  <img
                    src="https://labfile.oss.aliyuncs.com/courses/3944/layout.png "
                  />
                  <div class="block_content">
                    <h3>Title</h3>
                    <p class="meta">Month dd, yyyy</p>
                    <p class="summary">
                      Summary summary summary summary summary summary
                    </p>
                    <p class="main">
                      Content content content content content content content
                      content content content content content content content
                      content content
                    </p>
                    <a
                      href="#nogo"
                      title="Dummy placeholder link. This doesn't go anywhere."
                      >Link</a
                    >
                  </div>
                </div>
              </div>
              <!-- End: Single Block -->

              <!-- Start: Single Block -->
              <div class="block">
                <div class="block_inner">
                  <img
                    src="https://labfile.oss.aliyuncs.com/courses/3944/layout.png "
                  />
                  <div class="block_content">
                    <h3>Title</h3>
                    <p class="meta">Month dd, yyyy</p>
                    <p class="summary">
                      Summary summary summary summary summary summary
                    </p>
                    <p class="main">
                      Content content content content content content content
                      content content content content content content content
                      content content
                    </p>
                    <a
                      href="#nogo"
                      title="Dummy placeholder link. This doesn't go anywhere."
                      >Link</a
                    >
                  </div>
                </div>
              </div>
              <!-- End: Single Block -->

              <!-- Start: Single Block -->
              <div class="block">
                <div class="block_inner">
                  <img
                    src="https://labfile.oss.aliyuncs.com/courses/3944/layout.png "
                  />
                  <div class="block_content">
                    <h3>Title</h3>
                    <p class="meta">Month dd, yyyy</p>
                    <p class="summary">
                      Summary summary summary summary summary summary
                    </p>
                    <p class="main">
                      Content content content content content content content
                      content content content content content content content
                      content content
                    </p>
                    <a
                      href="#nogo"
                      title="Dummy placeholder link. This doesn't go anywhere."
                      >Link</a
                    >
                  </div>
                </div>
              </div>
              <!-- End: Single Block -->
            </div>
          </aside>
        </div>
      </div>

      <footer>
        <div id="footer_inner">
          <p>
            Built by <a href="#" title="Blog">Nicholas Davison</a> for
            <a href="#" title="Digitaria's Company Website">Digitaria</a>
          </p>
          <p>
            © Copyright
            <a href="#" title="Digitaria's Company Website">Digitaria</a>
          </p>
        </div>
      </footer>
    </div>
  </body>
</html>

index.css

body {
    background-color: #fff;
    color: #000;
    font-family: Arial;
    font-size: 14px;
    margin: 0;
  }
  a {
    color: #000088;
    text-decoration: none;
  }
  a:hover {
    text-decoration: underline;
  }
  a.mode,
  footer a {
    color: #0000ff;
  }
  header {
    margin: 20px 0 0 0;
  }
  #header_inner {
    background-color: #edd;
    border: 1px solid #800;
  }
  #menu_inner {
    background-color: #eed;
    border: 1px solid #880;
  }
  #article_inner {
    background-color: #ded;
    border: 1px solid #080;
  }
  #aside_inner {
    background-color: #dee;
    border: 1px solid #088;
  }
  footer {
    clear: both;
    margin: 0 0 20px 0;
  }
  #footer_inner {
    background-color: #dde;
    border: 1px solid #008;
  }
  #header_inner,
  #menu_inner,
  #article_inner,
  #aside_inner,
  #footer_inner {
    padding: 1px 20px;
  }
  header h1 {
    display: none;
  }
  .responsive header h1#header_responsive,
  .static header h1#header_static {
    display: block;
  }
  #overview {
    border-top: 1px solid #080;
    border-bottom: 1px solid #080;
    zoom: 1;
  }
  #overview:after {
    clear: both;
    content: ".";
    display: block;
    height: 0;
    overflow: hidden;
  }
  #overview h1 {
    display: none;
  }
  #overview p {
    display: none;
  }
  #overview img {
    display: none;
    float: left;
    margin: 20px 20px 20px 0;
    width: 110px;
  }
  .responsive #overview .overview_responsive,
  .static #overview .overview_static {
    display: block;
  }
  h1,
  h2,
  h3,
  h4,
  h5,
  h6,
  p {
    margin: 20px 0;
  }
  .block {
    clear: both;
    margin: 20px 0;
    zoom: 1;
  }
  .block:after {
    clear: both;
    content: ".";
    display: block;
    height: 0;
    overflow: hidden;
  }
  .block h3 {
    margin: 0;
  }
  .block p {
    margin: 0 0 20px 0;
  }
  .block p.meta {
    color: #888;
    font-size: 80%;
    margin: 0;
  }
  .responsive header {
    margin: 20px 0 0 0;
    padding: 0;
    position: relative;
  }
  .responsive menu,
  .responsive article,
  .responsive aside,
  .responsive footer {
    margin: 20px 0;
    padding: 0;
  }
  .static #page_wrapper {
    margin: 0 auto;
    width: 960px;
  }
  .static header {
    padding: 0;
    position: relative;
  }
  .static menu,
  .static aside {
    clear: none;
    float: left;
    margin: 20px 0;
    padding: 0;
    width: 200px;
    zoom: 1;
  }
  .static aside {
    float: right;
  }
  .static menu ul {
    margin: 20px 0;
    padding: 0;
  }
  .static menu ul li {
    list-style: none;
    margin: 0;
    padding: 0;
  }
  .static menu ul li ul {
    margin: 0 0 0 40px;
  }
  .static article {
    clear: none;
    float: left;
    margin: 20px;
    padding: 0;
    width: 520px;
  }
  .static article .block img {
    clear: left;
    float: left;
    width: 120px;
    zoom: 1;
  }
  .static article .block .block_content {
    clear: right;
    margin-left: 140px;
  }
  .static article .block p.summary {
    display: none;
  }
  .static #overview #layout_3 {
    display: block;
  }
  .static aside .block img {
    display: none;
  }
  .static aside .block p.main {
    display: none;
  }
  .static footer {
    clear: both;
    padding: 0;
  }
  .responsive menu ul {
    margin: 20px 0;
    padding: 0;
  }
  .responsive menu ul li {
    list-style: none;
    margin: 0;
    padding: 0;
  }
  .responsive menu ul li ul {
    margin: 0 0 0 40px;
  }
  .responsive article .block img {
    clear: left;
    float: left;
    width: 20%;
    zoom: 1;
  }
  .responsive article .block .block_content {
    clear: right;
    margin-left: 20.1%;
  }
  .responsive article .block .block_content h3,
  .responsive article .block .block_content p,
  .responsive article .block .block_content a {
    margin-left: 20px;
  }
  .responsive article .block p.summary {
    display: none;
  }
  .responsive aside .block img {
    display: none;
  }
  .responsive aside .block p.main {
    display: none;
  }
  .responsive #page_wrapper {
    margin: 0 20px;
  }

未完待续

这里是云端源想IT,帮你轻松学IT”

嗨~ 今天的你过得还好吗?

有些时候

为了看到光明

你必须冒险闯入黑暗之中

- 2024.03.29 -

CSS定位属性是用于控制网页中元素位置的一种方式,它能够让元素在页面上精准地落在我们想要的位置。

在CSS中,定位(Positioning)是控制元素在页面上如何定位和显示的一种机制。它主要包括四种属性:静态定位(static)、相对定位(relative)、绝对定位(absolute)、固定定位(fixed)。

每种定位方式都有其独特的特点和使用场景,下面将分别介绍这几种定位属性。


一、Static(静态定位)

静态定位是元素的默认定位方式,元素按照正常的文档流进行排列。在静态定位状态下,不能配合top、bottom、left、right来改变元素的位置。


  • 可以用于取消元素之前的定位设置。


代码示例:

<!DOCTYPE html>
<html>
<head>
<style>
.static {
background-color: lightblue;
padding: 100px;
}
</style>
</head>
<body>

<div>这是一个静态定位的元素。</div>

</body>
</html>

二、Fixed(固定定位)

固定定位使元素相对于浏览器窗口进行定位,即使页面滚动,元素也会保持在固定的位置。

  • 固定定位的元素会脱离正常的文档流。


示例代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
body{
/* 给整个页面设置高度,出滚动条以便观察 */
height: 5000px;
}
div{
width: 100px;
height: 100px;
background-color: blue;
/* 固定定位 */
position: fixed;
right: 100px;
bottom: 100px;
}
</style>
</head>
<body>
<div></div>
</body>
</html>

运行结果:

移动前

移动后

比如我们经常看到的网页右下角显示的“返回到顶部”,就可以用固定定位来实现。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body {
position: relative;
}
.content {
/* 页面内容样式 */
}
#backToTop {
position: fixed;
bottom: 20px;
right: 20px;
background-color: #333;
color: #fff;
border: none;
padding: 10px;
cursor: pointer;
}
</style>
</head>
<body style="height: 5000px;">
<div>
</div>
<button id="backToTop" onclick="scrollToTop()">返回顶部</button>
<script>
function scrollToTop() {
window.scrollTo({top: 0, behavior: 'smooth'});
}
</script>
</body>
</html>

运行结果:

三、Relative(相对定位)

相对定位是将元素对于它在标准流中的位置进行定位,通过设置边移属性top、bottom、left、right,使指定元素相对于其正常位置进行偏移。如果没有定位偏移量,对元素本身没有任何影响。

  • 不使元素脱离文档流,空间会保留,不影响其他布局。


代码示例:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box1{
width:200px;
height:100px;
background:skyblue;
margin:10px;
}
.box2{
width:200px;
height:100px;
background:pink;
margin:10px;
position:relative;/*相对定位*/
left:100px;/*向右偏移100px*/
top:-50px;/*向上偏移50px*/
}
.box3{
width:200px;
height:100px;
background:yellowgreen;
margin:10px;
}
</style>
</head>
<body>
<div>1</div>
<div>2</div>
<div>3</div>
</body>
</html>

运行结果:

没使用相对定位之前是这样的:

使用相对定位后:相对于原来的位置向右偏移了100px,向上偏移50px。

虽然它的位置发生了变化,但它在标准文档流中的原位置依然保留。


四、Absolute(绝对定位)

绝对定位使元素相对于最近的非 static 定位祖先元素进行定位。如果没有这样的元素,则相对于初始包含块(initial containing block)。绝对定位的元素会脱离正常的文档流。

  • 如果该元素为内联元素,则会变成块级元素,可直接设置其宽和高的值(让内联具备快特性);
  • 如果该元素为块级元素,使其宽度根据内容决定。(让块具备内联的特性)
<style>
.wrap{
width:500px;
height:400px;
border: 2px solid red;
}
.box1{
width:200px;
height:100px;
background:skyblue;
margin:10px;
}
.box2{
width:200px;
height:100px;
background:pink;
margin:10px;
position:absolute;/*绝对定位*/
left:100px;/*向右偏移100px*/
top:30px;/*向下偏移30px*/
}
.box3{
width:200px;
height:100px;
background:yellowgreen;
margin:10px;

}
</style>
<div>
<div>1</div>
<div>2</div>
<div>3</div>
</div>

将第二个设置为绝对定位后,它脱离了文档流可以定位到页面的任何地方,在标准文档流中的原有位置会空出来,所以第三个会排到第一个下面。

第二个相对于它的父元素向右偏移100,向下偏移30。

想要快速入门前端开发吗?推荐一个前端开发基础课程,这个老师讲的特别好,零基础学习无压力,知识点结合代码,边学边练,可以免费试看试学,还有各种辅助工具和资料,非常适合新手!点这里前往学习哦!云端源想

五、z-index(层级顺序的改变)

层叠顺序决定了元素之间的堆叠顺序。z-index 属性用于设置元素的层叠顺序。具有较高 z-index 值的元素会覆盖具有较低 z-index 值的元素。


注意:

  • 默认值是0
  • 数值越大层越靠上
  • 不带单位
  • 没有最大值和最小值
  • 可以给负数


代码示例:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div:nth-of-type(1){
width: 300px;
height: 300px;
background-color: skyblue;
position: absolute;
}
div:nth-of-type(2){
width: 200px;
height: 200px;
background-color: pink;
position: absolute;
}
div:nth-of-type(3){
width: 100px;
height: 100px;
background-color: yellowgreen;
position: absolute;
z-index: -1;
}
</style>
</head>
<body>
<div></div>
<div></div>
<div></div>

</body>
</html>

运行结果:

可以看到,最后一个div依然存在,但是看不见了,原因就是我们改变了z-index属性值。

以上就是CSS定位属性的介绍了,通过这些定位属性,可以灵活地控制网页中元素的位置和堆叠顺序。


在实际应用中,CSS定位属性的使用需要考虑到整体布局和用户体验。合理运用这些定位技巧,可以让你的网页不仅美观,而且易于使用和维护。记住,好的设计总是细节和功能的完美结合。


我们下期再见!

END

文案编辑|云端学长

文案配图|云端学长

内容由:云端源想分享