常见的行内元素:
div、p、h1~h6、ul、ol、dl、li、dd、table、hr、blockquote、address、table、menu、pre,HTML5新增的header、section、aside、footer
常见的块级元素:
span、img、a、lable、input、abbr(缩写)、em(强调)、big、cite(引用)、i(斜体)、q(短引用)、textarea、select、small、sub、sup,strong、u(下划线)、button(默认display:inline-block)
居 中 方 法 :
行内元素:
-
父级元素 设置 text-align: center;
.parent { text-align: center; } -
行内元素(单行文字垂直居中):设置 line-height = height
.parent {
height: 200px;
line-height: 200px;
border: 1px solid red;
}
块级元素:!!!!!
- margin: auto; 低版本浏览器父级元素还需要设置 `text-align: center
垂直居中的方案:
-
块级元素:绝对定位(需要提前知道尺寸)
需要提前知道尺寸,
margin-top: -(高度的一半);margin-left: -(宽度的一半);
.parent {
position: relative;
height: 200px;
}
.child {
width: 80px;
height: 40px;
background: blue;
position: absolute;
left: 50%;
top: 50%;
margin-top: -20px;
margin-left: -40px;
}
2.块级元素:display: flex
缺点:兼容性不好
.parent {
width: 600px;
height: 200px;
border: 1px solid red;
display: flex;
align-items: center; /* 垂直居中 */
justify-content: center; /*水平居中*/
}
.child {
background: blue;
}
-
3.块级元素:绝对定位 + margin: auto;
-
优点:不需要提前知道尺寸,兼容性好
-
缺点:这个方法是我最喜欢用的一个,要说缺点的话,我目前还不知道。
.parent { position: relative; height: 200px; } .child { width: 80px; height: 40px; position: absolute; left: 0; top: 0; right: 0; bottom: 0; margin: auto; background: blue; }
-
4.块级元素:padding
缺点需要计算尺寸
<style>
.parent {
width: 650px;
height: 400px;
background: yellow;
padding-left: 150px;
padding-top: 100px;
}
.child {
width: 500px;
height: 300px;
background-color: deeppink;
}
</style>
<body>
<div class="parent"> 可见宽度是800 就是上下各距离了150
<div class="child">child</div>
</div>
</body>
5.块级元素:display: table-cell
配合使用 display: table; display: table-cell;
display:table相当于
,display:table-cell,就相当于|
为什么可以呢: 因为table中的特殊性: 单元格有一些比较特别的属性,例如元素的垂直居中对齐
6.块级元素:绝对定位 + transform
7.块级元素:inline-block
\ |