2018-10-10 22:03:03 +00:00
|
|
|
---
|
|
|
|
id: 587d78a3367417b2b2512ad0
|
2020-12-16 07:37:30 +00:00
|
|
|
title: 使用 margin 属性将元素水平居中
|
2018-10-10 22:03:03 +00:00
|
|
|
challengeType: 0
|
2020-02-11 07:46:34 +00:00
|
|
|
videoUrl: 'https://scrimba.com/c/cyLJqU4'
|
|
|
|
forumTopicId: 301043
|
2021-01-13 02:31:00 +00:00
|
|
|
dashedName: center-an-element-horizontally-using-the-margin-property
|
2018-10-10 22:03:03 +00:00
|
|
|
---
|
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
# --description--
|
2018-10-10 22:03:03 +00:00
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
在应用设计中经常需要把一个块级元素水平居中显示。一种常见的实现方式是把块级元素的 `margin` 值设置为 `auto`。
|
2018-10-10 22:03:03 +00:00
|
|
|
|
2021-01-08 19:20:48 +00:00
|
|
|
同样的,这个方法也对图片奏效。图片默认是内联元素,但是可以通过设置其 `display` 属性为 `block` 来把它变成块级元素。
|
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
|
|
|
通过将页面中 `div` 的 `margin` 属性值设置为 `auto` 来让它居中显示。
|
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
|
|
|
`div` 的 `margin` 属性值应为 `auto`。
|
2018-10-10 22:03:03 +00:00
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
```js
|
|
|
|
assert(code.match(/margin:\s*?auto;/g));
|
2018-10-10 22:03:03 +00:00
|
|
|
```
|
|
|
|
|
2021-01-13 02:31:00 +00:00
|
|
|
# --seed--
|
|
|
|
|
|
|
|
## --seed-contents--
|
|
|
|
|
|
|
|
```html
|
|
|
|
<style>
|
|
|
|
div {
|
|
|
|
background-color: blue;
|
|
|
|
height: 100px;
|
|
|
|
width: 100px;
|
|
|
|
|
|
|
|
}
|
|
|
|
</style>
|
|
|
|
<div></div>
|
|
|
|
```
|
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
# --solutions--
|
2020-02-11 07:46:34 +00:00
|
|
|
|
2021-01-13 02:31:00 +00:00
|
|
|
```html
|
|
|
|
<style>
|
|
|
|
div {
|
|
|
|
background-color: blue;
|
|
|
|
height: 100px;
|
|
|
|
width: 100px;
|
|
|
|
margin: auto;
|
|
|
|
}
|
|
|
|
</style>
|
|
|
|
<div></div>
|
|
|
|
```
|