一。 居中(子元素在父元素中水平垂直居中)
方法1 : 定位+transform
.father{
width: 500px;
height: 500px;
background-color: red;
position: relative;
}
.son{
width: 200px;
height: 200px;
background-color: blue;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
方法2:弹性盒子
.father{
width: 500px;
height: 500px;
background-color: red;
display: flex;
justify-content: center;
align-items: center;
}
方法3:绝对定位
.father{
width: 500px;
height: 500px;
background-color: red;
position: relative;
}
.son{
width: 200px;
height: 200px;
background-color: blue;
position: absolute;
margin: auto;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
二。水平居中
注:必须是已知宽度的块元素才会生效
margin : 0 auto
三。设置CSS 盒子模型
box-sizing: content-box;
注:默认值,假如设置一个元素的宽为 100px,元素的内容区会有 100px 宽,并且任何边框和内 边距的宽度都会被增加到最后绘制出来的元素宽度中
box-sizing: border-box;
注:假如设置盒子宽100px,这 100px 会包含它的 border 和 padding内容区的实际宽度是 width 减去 (border + padding) 的值
四。文本水平居中
注:仅指定行内元素(inline)或表格单元格(table-cell)元素
text-align: center;
line-height: 500px;(父元素的高度)
注:vertical-align
只对行内元素、行内块元素和表格单元格元素生效:不能用它垂直对齐块级元素
text-align: center;
vertical-align: middle;
五。三角形
width: 0px;
height: 0px;
border: 10px solid transparent;
border-bottom-color: black;
六。优先级
注:一般用于定位元素的层级,不能改变浮动元素 / 无法改变祖先的层级,遮盖它,一般在兄弟之间使用 / 使用负值会降低优先级
z-index: -1;
z-index:100;
七。解决高度塌陷 (before)/ 边距折叠(after)
.clearfix::after,.clearfix::before{
content: ' ';
clear: both;
display: table;
}
注:在使用了浮动导致高度塌陷或 边框折叠(父与子元素)加上.clearfix类即可。
八。指定元素后面的背景的被覆盖程度
注:值为0.0 到 1.0 范围内的数字值
opacity: 0.5;
opacity: 1; 完全不透明
九。阴影效果
/* x 偏移量 | y 偏移量 | 阴影颜色 */
box-shadow: 60px -16px teal;
/* x 偏移量 | y 偏移量 | 阴影模糊半径 | 阴影颜色 */
box-shadow: 10px 5px 5px black;
/* x 偏移量 | y 偏移量 | 阴影模糊半径 | 阴影扩散半径 | 阴影颜色 */
box-shadow: 2px 2px 2px 1px rgba(0, 0, 0, 0.2);
/* 插页 (阴影向内) | x 偏移量 | y 偏移量 | 阴影颜色 */
box-shadow: inset 5em 1em gold;
/* 任意数量的阴影,以逗号分隔 */
box-shadow: 3px 3px red, -1em 0 0.4em olive;
十。元素轮廓
注:不占实际空间
/* 颜色 | 样式 | 宽度 */
outline: green solid 3px;
/* 样式 */
outline: solid;
十一。去除列表元素li的符号
list-style: none;
十二。去除a链接的下划线
text-decoration: none;
十二。隐藏元素
visibility: hidden;(隐藏后依然占据空间,影响布局)
display:none(隐藏后不占空间,不影响布局)
十三。防止文字溢出
注:为使 overflow
有效果,块级容器必须有一个指定的高度(height
或者max-height
)或者将white-space
设置为nowrap
。
overflow: hidden;