codecamp

Practical positioning examples

先决条件: HTML基础知识(了解 HTML简介)以及CSS的工作原理(了解 CSS简介 >。)
目的: 了解定位的实用性

带有标签的信息框

我们将看到的第一个例子是一个经典的标签式信息框 - 这是一个非常常见的功能,当您想将大量信息包装到一个小区域时使用。 这包括信息量大的应用程序,如战略/战争游戏,手机版的网站,屏幕狭窄,空间有限,以及紧凑的信息框,你可能想要使大量的信息可用,而无需填充整个UI。 我们的简单示例在完成后将如下所示:

;">

注意:您可以在 -box.html"class ="external"> info-box.html ( practical-positioning-examples / info-box.html"class ="external">源代码)。 检查出来,以了解你将在本文的这一部分中构建什么。

你可能会想,"为什么不只是将单独的选项卡创建为单独的网页,而只是让标签单击到单独的页面来创建效果? 这个代码会更简单,是的,但是每个单独的"页面"视图实际上将是一个新加载的网页,这将使得难以跨视图保存信息,并将此功能集成到一个更大的UI设计。 此外,所谓的"单页应用"变得非常流行 - 尤其是对于移动网络用户界面 - 因为将所有内容作为单个文件,减少了查看所有内容所需的HTTP请求数,从而提高性能。

注意:某些网络开发人员会更进一步,只需一次加载一页信息,并使用JavaScript功能(如 mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest\">XMLHttpRequest 在你的学习的这一点上,我们希望保持尽可能简单的东西。 以后有一些JavaScript,但只有一点点。

首先,我们希望您制作起始HTML文件的本地副本 - -positioning-examples / info-box-start.html"class ="external"> info-box-start.html 将这个地方保存在本地计算机上的某个地方,并在文本编辑器中打开它。 让我们来看看包含在正文中的HTML:

<section class="info-box">
  <ul>
    <li><a href="#" class="active">Tab 1</a></li>
    <li><a href="#">Tab 2</a></li>
    <li><a href="#">Tab 3</a></li>
  </ul>
  <div class="panels">
    <article class="active-panel">
      <h2>The first tab</h2>

      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque turpis nibh, porttitor nec venenatis eu, pulvinar in augue. Vestibulum et orci scelerisque, vulputate tellus quis, lobortis dui. Vivamus varius libero at ipsum mattis efficitur ut nec nisl. Nullam eget tincidunt metus. Donec ultrices, urna maximus consequat aliquet, dui neque eleifend lorem, a auctor libero turpis at sem. Aliquam ut porttitor urna. Nulla facilisi.</p>
    </article>
    <article>
      <h2>The second tab</h2>

      <p>This tab hasn't got any Lorem Ipsum in it. But the content isn't very exciting all the same.</p>
    </article>
    <article>
      <h2>The third tab</h2>

      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque turpis nibh, porttitor nec venenatis eu, pulvinar in augue. And now an ordered list: how exciting!</p>

      <ol>
        <li>dui neque eleifend lorem, a auctor libero turpis at sem.</li>
        <li>Aliquam ut porttitor urna.</li>
        <li>Nulla facilisi</li>
      </ol>
    </article>
  </div>
</section>

首先,我们希望您制作起始HTML文件的本地副本 - -positioning-examples / info-box-start.html"class ="external"> info-box-start.html 。 将这个地方保存在本地计算机上的某个地方,并在文本编辑器中打开它。 让我们来看看包含在正文中的HTML:

这里的想法是,我们将样式的标签看起来像一个标准的水平导航菜单,并使样式的面板,以使用绝对定位的另一个顶部。 我们还会给你一些JavaScript来包含在页面上,以便在按下标签时显示相应的面板,并设置标签本身的样式。 在这个阶段,您不需要了解JavaScript本身,但您应该考虑尽快学习一些基本的 JavaScript - 您的UI功能变得越复杂 ,更可能需要一些JavaScript来实现所需的功能。

一般设置

首先,在打开和关闭之间添加以下内容 默认情况下,写在该元素内的样式指令应为CSS。"> < style> 标签:

html {
  font-family: sans-serif;
}

* {
  box-sizing: border-box;
}

body {
  margin: 0;
}

这只是一些通用设置,在我们的页面上设置无衬线字体,使用 border-box Web / CSS / box-sizing"title ="box-sizing属性用于更改用于计算元素宽度和高度的默认CSS框模型。可以使用此属性来模拟浏览器的行为 不正确支持CSS盒子模型规范"> box-sizing 模型,并摆脱默认的 CN / docs / Web / HTML / Element / body"title ="HTML元素表示HTML文档的内容,文档中只能有一个元素。"> < body> / a> margin。

接下来,在您之前的CSS下面添加以下内容:

.info-box {
  width: 450px;
  height: 400px;
  margin: 0 auto;
}

这会在内容上设置特定的宽度和高度,并使用旧的 margin:0 auto 技巧将其居中在屏幕上。 以前在课程中,我们建议不要在内容容器上设置固定高度,如果可能的话; 这是确定在这种情况下,因为我们有固定的内容在我们的选项卡。 它也看起来有点不舒服,有不同的标签在不同的高度。

为样式设置选项卡

现在我们要将标签样式看起来像标签页 - 基本上,这些是一个水平导航菜单,但是不是像我们以前在课程中看到的那样加载不同的网页,它们会导致不同的面板显示在 同一页。 首先,在CSS底部添加以下规则,删除默认的 -left元素的CSS属性设置元素左侧所需的填充空间,填充区域是元素内容和边界之间的空格,不允许使用负值"> padding- left 元素设置元素顶部所需的边距空间,也允许使用负值。"> margin-top 从无序列表:

.info-box ul {
  padding-left: 0;
  margin-top: 0;
}

注意:在此示例中,我们在链的开头使用带有 .info-box 的后代选择器 - 这样我们可以将此功能插入到其他 内容,而不必担心干扰应用到页面其他部分的样式。

注意:在此示例中,我们在链的开头使用带有 .info-box 的后代选择器 - 这样我们可以将此功能插入到其他 内容,而不必担心干扰应用到页面其他部分的样式。

添加以下CSS:

.info-box li {
  float: left;
  list-style-type: none;
  width: 150px;
}

.info-box li a {
  display: inline-block;
  text-decoration: none;
  width: 100%;
  line-height: 3;
  background-color: red;
  color: black;
  text-align: center;
}

最后对于这一节,我们将在链接状态上设置一些样式。 首先,当焦点/悬停时,我们将设置标签的:focus :hover 状态看起来不同,为用户提供一些视觉反馈。 其次,当活动存在时,我们将设置一个规则,在其中一个选项卡上放置相同的样式。 我们将在单击选项卡时使用JavaScript设置。 将以下CSS放置在其他样式下面:

.info-box li a:focus, .info-box li a:hover {
  background-color: #a60000;
  color: white;
}

.info-box li a.active {
  background-color: #a60000;
  color: white;
}

设计面板样式

下一个工作是为我们的面板设计风格。 我们走吧!

下一个工作是为我们的面板设计风格。 我们走吧!

.info-box .panels {
  height: 352px;
  position: relative;
  clear: both;
}

下一个工作是为我们的面板设计风格。 我们走吧!

我们将在这里添加的第二条规则是,其中设置了 active-panel 的面板将具有 developer.mozilla.org/zh-CN/docs/Web/CSS/z-index"title ="z-index属性指定定位的元素及其后代的z顺序,当元素重叠时,z顺序确定哪个 一个覆盖另一个。具有较大z-索引的元素通常覆盖具有较低索引的元素。"> z-index 为1,应用于它, 其他面板(定位的元素默认情况下具有 z-index 0,这将把它们放在下面)。 同样,我们将在适当的时间使用JavaScript添加此类。

.info-box article {
  position: absolute;
  top: 0;
  left: 0;
  height: 352px;
  padding: 10px;
  color: white;
  background-color: #a60000;
}

.info-box .active-panel {
  z-index: 1;
}

添加JavaScript

获取此功能的最后一步是添加一些JavaScript。 放置以下代码块,与打开和关闭之间写的一样。 script元素用于嵌入或引用可执行脚本"> < script> 标记(您会在HTML内容下方找到这些标记):

var tabs = document.querySelectorAll('.info-box li a');
var panels = document.querySelectorAll('.info-box article');

for(i = 0; i < tabs.length; i++) {
  var tab = tabs[i];
  setTabHandler(tab, i);
}

function setTabHandler(tab, tabPos) {
  tab.onclick = function() {
    for(i = 0; i < tabs.length; i++) {
      if(tabs[i].getAttribute('class')) {
        tabs[i].removeAttribute('class');
      }
    }

    tab.setAttribute('class', 'active');

    for(i = 0; i < panels.length; i++) {
      if(panels[i].getAttribute('class')) {
        panels[i].removeAttribute('class');
      }
    }

    panels[tabPos].setAttribute('class', 'active-panel');
  }
}

此代码执行以下操作:

  • First we save a reference to all the tabs and all the panels in two variables called tabs and panels, so we can easily do things to them later on.
  • Then we use a for loop to cycle through all the tabs and run a function called setTabHandler() on each one, which sets up the functionality that should occur when each one is clicked on. When run, the function is passed a reference to the particular tab it is being run for, and an index number i that indentifies the tab's position in the tabs array.
  • In the setTabHandler() function, the tab has an onclick event handler set on it, so that when the tab is clicked, the following occurs:
    • A for loop is used to cycle through all the tabs and remove any classes that are present on them.
    • A class of active is set on the tab that was clicked on — remember from earlier that this class has an associated rule in the CSS that sets the same color and background-color on the tab as the panels are styled with.
    • A for loop is used to cycle through all the panels and remove any classes that are present on them.
    • A class of active-panel is set on the panel that corresponds to the tab that was clicked on — remember from earlier that this class has an associated rule in the CSS that sets its z-index to 1, making it appear over the top of the other panels.

这是第一个例子。 保持你的代码打开,我们将添加到它在第二个。

固定位置标签信息框

在第二个示例中,我们将使用我们的第一个示例 - 我们的信息框,并将其添加到完整网页的上下文中。 但不仅如此 - 我们会给它固定的位置,使它在浏览器窗口中保持在相同的位置。 当主内容滚动时,信息框将保持在屏幕上的相同位置。 我们完成的示例将如下所示:

height:585px; margin:0px auto; width:1118px;">

作为起点,您可以使用本文第一部分中完整的示例,也可以创建本地副本 css-layout / practical-positioning-examples / info-box.html"class ="external"> info-box.html 从我们的Github仓库。

HTML添加

首先,我们需要一些额外的HTML来表示网站的主要内容。 添加以下 内容的主题分组,通常带有标题。> < section> docs / Web / HTML / Element / body"title ="HTML元素表示HTML文档的内容。文档中只能有一个元素。"> < body> >标记,就在现有部分之前:

<section class="fake-content">
  <h1>Fake content</h1>
  <p>This is fake content. Your main web page contents would probably go here.</p>
  <p>This is fake content. Your main web page contents would probably go here.</p>
  <p>This is fake content. Your main web page contents would probably go here.</p>
  <p>This is fake content. Your main web page contents would probably go here.</p>
  <p>This is fake content. Your main web page contents would probably go here.</p>
  <p>This is fake content. Your main web page contents would probably go here.</p>
  <p>This is fake content. Your main web page contents would probably go here.</p>
  <p>This is fake content. Your main web page contents would probably go here.</p>
</section>

注意:如果您愿意,可以随意更改某些实际内容的假内容。

对现有CSS的更改

接下来,我们需要对现有CSS进行一些小的更改,以获取放置和定位的信息框。 更改您的 .info-box 规则以摆脱 margin:0 auto; (我们不再希望信息框居中),添加 //developer.mozilla.org/zh-CN/docs/Web/CSS/position"title ="position CSS属性为定位元素选择替代规则,旨在对脚本动画效果有用。"> position :fixed; ,然后粘贴到 title ="顶部CSS属性指定已定位元素的位置的一部分,它对浏览器视口的非定位元素没有影响"> top

它现在应该看起来像这样:

.info-box {
  width: 450px;
  height: 400px;
  position: fixed;
  top: 0;
}

设计主要内容

这个例子只剩下为主要内容提供一些样式。 在CSS的其余部分下面添加以下规则:

.fake-content {
  background-color: #a60000;
  color: white;
  padding: 10px;
  height: 2000px;
  margin-left: 470px;
}

首先,我们给内容相同background-color, 通过颜色值或关键字transparent来定义元素的背景颜色。"> background-color CN / docs / Web / CSS / color"title ="color属性设置元素的文本内容的前景颜色及其装饰,它不会影响元素的任何其他特性;它实际上应该被称为文本颜色color, and 除了历史原因以及它在CSS级别1中的外观外,还会被命名为"> color zh-CN / docs / Web / CSS / padding"title ="padding属性设置元素所有边上的填充空间,填充区域是元素内容和边框之间的空格,不允许使用负值padding as the info-box panels.\">。"> padding 作为信息框面板。然后我们给它一个大的margin-left to move it over to the right, making space for the info-box to\">与元素关联的框的左侧,也允许使用负值。"> margin-left 将其移动到右侧,为信息框留出空间坐在,所以它不重叠任何东西。

这标志着第二个例子的结束; 我们希望你会发现第三个也很有趣。

一个滑动隐藏面板

我们在这里展示的最后一个例子是一个面板,在一个图标的按下,在屏幕上滑动和滑动 - 如前所述,这是受欢迎的情况,如移动布局,可用的屏幕空间很小, 想通过显示菜单或信息面板而不是有用的内容来使用它的大部分。

我们完成的示例将如下所示:

height:521px; margin:0px auto; width:950px;">

作为起点,请创建 -start.html"class ="external"> hidden-info-panel-start.html 从我们的Github仓库。 这不从前面的例子继续,因此需要一个新的开始文件。 让我们看看文件中的HTML:

<label for="toggle">❔</label>
<input type="checkbox" id="toggle">
<aside>

  ...

</aside>

从这里开始,我们有一个 项目在用户界面中。"> < label> 元素和 / Element / input"title ="HTML输入元素用于为基于Web的表单创建交互式控件,以便接受来自用户的数据。输入的工作原理根据类型属性的值而有很大不同。"> 代码>< input> element - < label> 元素通常用于将文本标签与表单元素相关联, 什么描述与什么形式元素)。 这里,它使用 for id 属性与< input>

注意:我们在HTML中添加了一个特殊的问号字符,作为我们的信息图标 - 这代表将按下以显示/隐藏面板的按钮。

这里我们将使用这些元素的目的稍有不同 - < label> 元素的另一个有用的副作用是,您可以单击复选框的标签以选中复选框, 本身。 这导致了众所周知的复选框hack ,它提供了一种无JavaScript的方式 通过切换按钮来控制元素。 我们要控制的元素是 文档,其内容与文档的主要内容相切(通常作为侧边栏)。"> < aside> 元素跟随其他两个 出于简洁起见上面的代码列表)。

在下面的部分,我们将解释这一切如何工作。

为表单元素设置样式

首先让我们处理表单元素 - 在 元素包含文档或文档的一部分的样式信息默认情况下,写在该元素内的样式指令应为CSS。"> < style> tags:

label[for="toggle"] {
  font-size: 3rem;
  position: absolute;
  top: 4px;
  right: 5px;
  z-index: 1;
  cursor: pointer;
}

input[type="checkbox"] {
  position: absolute;
  top: -100px;
}

第一个规则样式为< label> ; 这里我们有:

  • Set a large font-size to make the icon nice and big.
  • Set position absolute on it, and used top and right to position it nicely in the top-right corner.
  • Set a z-index of 1 on it — this is so that when the info panel is styled and shown, it doesn't cover up the icon; instead the icon will sit on top of it so it can be pressed again to hide the info pane.
  • Used the cursor property to change the mouse cursor when it is hovering over the icon to a hand pointer (like the one you see when links are hovered over), as an extra visual clue to users that the icon does something interesting.

第二个规则设置 脚本化的动画效果"> position absolute ,并将其隐藏在顶部 屏幕。 我们实际上不想在我们的UI上看到这个。

为面板设置样式

现在是时候实际滑动面板本身的风格。 将以下规则添加到CSS的底部:

aside {
  background-color: #a60000;
  color: white;

  width: 340px;
  height: 98%;
  padding: 10px 1%;

  position: fixed;
  top: 0;
  right: -370px;

  transition: 0.6s all;
}

这里有很多事情 - 让我们逐一讨论一下:

  • First, we set some simple background-color and color on the info box.
  • Next, we set a fixed width on the panel, and make its height the entire height of the browser viewport.
  • We also include some padding to make up the width/height to the total value we want (this was necessary as we've not set box-sizing: border-box; on this example).
  • Next we set position: fixed; on the panel so it will always appear in the same place, even if the page has content to scroll. We glue it to the top of the viewport, and set it so that by default it is offscreen to the right.
  • Finally, we set a transition on the element. Transitions are an interesting feature that allow you to make changes between states happen smoothly, rather than just going "on", "off" abruptly. In this case we are intending to make the panel slide smoothly onscreen when the checkbox is checked. (Or to put it another way, when the question mark icon is clicked — remember, clicking the <label> will check the associated checkbox! We told you it was a hack.) You will learn a lot more about...

设置检查状态

有一个最后一点的CSS添加 - 把以下在CSS的底部:

input[type=checkbox]:checked + aside {
  right: 0px;
}

<aside> element adjacent to the <input> element, but only when it is checked (note the use of\">这里的选择器非常复杂 - 我们选择与< input> 元素相邻的< aside> 元素,但只有当它被选中),复选框(输入类型="复选框")或选项(选择中的选项)元素,选中或切换到打开状态。用户可以通过单击元素或选择不同的值来更改此状态,其中:checked pseudo-class to achieve this).\">case:checked伪类不再适用于这个元素,而是将对相关的一个。\'> :checked 伪类来实现这一点)。在这种情况下,我们设置right property of the <aside> to 0px, which causes the panel to appear on the screen\">定位元素"> right 属性设置为 0px ,这导致面板出现在屏幕上再次(由于转变而平滑)。再次单击标签会取消选中复选框,这会再次隐藏面板。

所以你有它 - 一个相当聪明的JavaScript免费的方式来创建一个切换按钮效果。 这将工作在IE9及以上(平滑过渡将工作在IE10及以上。)这种效果有一些关注 - 这是一个滥用的形式元素(他们不是为了这个目的),和效果 在可访问性方面不是很好 - 标签在默认情况下不可聚焦,并且表单元素的非语义使用可能导致屏幕阅读器的问题。 JavaScript和链接或按钮可能更合适,但它仍然是有趣的实验。

概要

所以,我们看看定位 - 现在,你应该有一个基本的机制如何工作的想法,以及理解如何开始应用这些来构建一些有趣的UI功能。 不要担心,如果你没有立即得到这一切 - 定位是一个相当高级的话题,你可以总是通过文章再次帮助你的理解。 接下来的主题是Flexbox。

Positioning
Flexbox
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录
CSS

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }