2018-10-10 22:03:03 +00:00
---
id: 587d781e367417b2b2512ac9
2020-12-16 07:37:30 +00:00
title: 更改元素的相对位置
2018-10-10 22:03:03 +00:00
challengeType: 0
2020-02-11 07:46:34 +00:00
videoUrl: 'https://scrimba.com/c/czVmMtZ'
forumTopicId: 301044
2021-01-13 02:31:00 +00:00
dashedName: change-an-elements-relative-position
2018-10-10 22:03:03 +00:00
---
2020-12-16 07:37:30 +00:00
# --description--
2021-01-08 19:20:48 +00:00
在 CSS 里一切 HTML 元素皆为盒子,也就是通常所说的< dfn > 盒模型< / dfn > 。块级元素自动从新的一行开始(比如标题、段落以及 div) , 行内元素排列在上一个元素后( 比如图片以及 span) 。元素默认按照这种方式布局称为文档的< dfn > 普通流< / dfn > ,同时 CSS 提供了 position 属性来覆盖它。
2020-12-16 07:37:30 +00:00
2021-01-08 19:20:48 +00:00
当元素的 position 设置为 `relative` 时,它允许你通过 CSS 指定该元素在当前普通流页面下的相对偏移量。CSS 里控制各个方向偏移量的属性是 `left` 、`right`、`top` 和 `bottom` 。它们代表从原来位置向远离该方向偏移指定的像素、百分比或者 em。下面的例子展示了段落向上偏移 10 像素:
2020-02-11 07:46:34 +00:00
```css
p {
position: relative;
bottom: 10px;
}
```
2021-01-08 19:20:48 +00:00
把元素的 position 设置成 relative 并不会改变该元素在普通流布局所占的位置,也不会对其它元素的位置产生影响。 ** 注意:**定位可以让你在页面布局上更灵活、高效。注意不管元素的定位是怎样,内部的 HTML 代码阅读起来应该是整洁、有意义的。这样也可以让视障人员(他们重度依赖辅助设备比如屏幕阅读软件)也能够无障碍地浏览你的网页。
2018-10-10 22:03:03 +00:00
2020-12-16 07:37:30 +00:00
# --instructions--
2018-10-10 22:03:03 +00:00
2021-01-08 19:20:48 +00:00
把 `h2` 的 `position` 属性值设置成 `relative` ,使用相应的 CSS 属性调整 `h2` 的位置,使其相对原本的位置向下偏移 15 像素。注意不要对 h1 和 p 元素的位置产生影响。
2018-10-10 22:03:03 +00:00
2020-12-16 07:37:30 +00:00
# --hints--
2018-10-10 22:03:03 +00:00
2021-01-08 19:20:48 +00:00
`h2` 元素应该添加 `position` 属性,其属性值应为 `relative` 。
2018-10-10 22:03:03 +00:00
2020-12-16 07:37:30 +00:00
```js
assert($('h2').css('position') == 'relative');
2018-10-10 22:03:03 +00:00
```
2020-12-16 07:37:30 +00:00
你应该使用 CSS 属性调整 `h2` 的位置使其从原来的位置向下偏移 `15px` 。
2018-10-10 22:03:03 +00:00
2020-12-16 07:37:30 +00:00
```js
assert($('h2').css('top') == '15px');
2018-10-10 22:03:03 +00:00
```
2020-02-11 07:46:34 +00:00
2021-01-13 02:31:00 +00:00
# --seed--
## --seed-contents--
```html
< style >
h2 {
}
< / style >
< body >
< h1 > On Being Well-Positioned< / h1 >
< h2 > Move me!< / h2 >
< p > I still think the h2 is where it normally sits.< / p >
< / body >
```
2020-12-16 07:37:30 +00:00
# --solutions--
2021-01-13 02:31:00 +00:00
```html
< style >
h2 {
position: relative;
top: 15px;
}
< / style >
< body >
< h1 > On Being Well-Positioned< / h1 >
< h2 > Move me!< / h2 >
< p > I still think the h2 is where it normally sits.< / p >
< / body >
```