在介绍css元素居中方法时,我们先来回忆一下几种常见的元素以及他们的特点,这样有助于我们理解这些方法的原理
一、几种常见的元素类型
1.块状元素 block
特点:
- 每个块状元素独占一行,多个块状元素标签写在一起,默认排列方式为从上至下;
- 元素的宽度如果不设置的话,默认为父元素的宽度;
1 2 3 4 5 6 7
| <div> // 布局结构块 <hr> // 创建一条水平线 <p> // 段落结构块 <form> // 创建 HTML 表单 <h1>、<h2>、<h3> // 标题结构块 <li>、<ol> 、<ul> // 列表结构块 <table>、<thead>、<tbody>、<td>、<th>、<tr> // 表格
|
2.行内元素 inline
行内元素的高度一般由元素内部的字体大小决定,宽度由内容的长度控制
特点:
- 不会独占一行,相邻的行内元素会排列在同一行里,直到一行排不下才会自动换行,其宽度随元素的内容而变化;
常见行内元素
1 2 3 4 5 6
| <a> // 超链接 <span>、<img> <br> // 换行 <q>、 <i> 引用 、斜体 <select>、<button>、<label> //表单对象包含框
|
3.行内块元素(inline-block)
inline-block元素具备了块元素与行内元素的特性,既能够设置宽高,又不独自占据一行。
二、水平居中
1.行内元素
1.1 方法一
只需要把行内元素包裹在一个属性display为block的父层元素中,并且把父层元素添加如下属性即可
1 2 3
| .parent { text-align:center; }
|
2.块状元素
1.1 方法一
最简单的方法就是将左右外边距设置为auto
1 2 3 4
| .child { margin:0 auto; }
|
1.1 方法二
父元素使用相对定位,子元素使用绝对定位后,将子元素的left和right设置为0,然后将上下margin设置为auto。(若父元素没有设置高度,记得考虑高度塌陷的问题)
1 2 3 4 5 6 7 8 9
| .parent{ position: relative; } .child{ position: absolute; left: 0;right: 0; margin: 0 auto; }
|
三、垂直居中
行内元素
将行内元素的父元素(块元素)的line-height与height设置为相同值(这时可以直接省略父元素的height,即只设置lne-height)。
1 2 3 4
| .parent { height: 100px; line-height: 100px; }
|
四、垂直水平居中
1.定位
子绝父相之后,设置水平和垂直方向上的偏移,偏移量分别为父元素宽度(高度)的一半减去子元素宽度(高度)的一半。这里使用到了**calc()**计算属性,注意使用时,在加号与减号的前后一定要有空格。
使用的条件:需要知道子元素的宽高
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| .parent{ position: relative; height: 200px; } .child{ position: absolute; width: 100px; height: 100px; position: absolute; left: calc(50% - 50px); top: calc(50% - 50px); }
.parent{ position: relative; height: 200px; } .child{ position: absolute; width: 100px; height: 100px; position: absolute; left: 50%;top: 50%; margin-top: -50px; margin-left: -50px; }
|
2.定位+margin
与第一种方法相对,下面的方法无需知道子元素的宽高,即可实现垂直水平居中
1 2 3 4 5 6 7 8 9 10 11 12 13
| .parent{ position: relative; height: 200px; } .child{ position: absolute; width: 100px; height: 100px; position: absolute; left: 0;right: 0; top: 0;bottom: 0; margin: auto; }
|
1 2 3 4 5 6 7 8 9 10 11 12 13
| .parent{ position: relative; height: 200px; } .child{ position: absolute; width: 100px; height: 100px; position: absolute; left: 50%; top: 50%; transform: translate(-50%,-50%); }
|
4.padding
1 2 3 4 5 6 7 8 9
| .parent { padding: 20px; background-color: red; }
.child { height: 200px; background-color: blue; }
|
5.flex布局
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| .parent { width: 200px; height: 200px; background-color: red; display: flex; justify-content: center; align-items: center; }
.child { width: 100px; height: 100px; background-color: blue; }
.parent { width: 200px; height: 200px; background-color: red; display: flex; }
.child { width: 100px; height: 100px; background-color: blue; margin:auto; }
|