CSS常见调试

一、居中

水平居中

  1. 行内元素: text-align:center
  2. 块级元素: margin: 0 auto;
  3. 弹性盒子:
1
2
display: flex;
justify-content: center;
  1. 绝对定位
1
2
3
4
5
6
7
8
.inner {
position: absolute;
width: 200px;
left: 50%;
margin-left: -100px;

}
/* absolute + left: calc() */
  1. 绝对定位 + translate

tips: 假如块级子元素宽高不定,如何实现居中?

1
2
3
4
5
6
7
8
9
10
11
12
13
.outer {
width: 100px;
height: 100px;
display: relative;
}

.inner {
position: absolute;
left:50%;
top: 50%;
/* tranlsate 将会平移自己宽度 高度的50% */
transform:translate(-50%, -50%);
}

垂直居中

  1. 单行文本:line-height
  2. 行内块级元素: 利用伪元素(占位) + vertical-align + inline-block
1
2
3
4
5
6
7
8
9
10
.outer::after,
.inner {
display: inline-block;
vertical-align: middle;
}

.outer::after {
content: '';
height: 100%;
}
  1. 弹性盒子
1
2
display: flex;
align-items: center;
  1. absolute定位
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    .outer {

    position: relative;

    }
    .inner{

    position:absolute;
    top:50%;
    height:200px;
    margin-top: -100px;

    }

/* absolute + top: calc() */

二、 关于position 的属性值

static

静态定位(position:static)是HTML中的默认定位,符合常规文档流
占据自己的区块,元素与元素之间不重叠

relative

相对定位(position:relative),
元素相对于默认位置(即static)而言,
搭配top、bottom、left、right进行上下左右的偏移,
不脱离文档流!

absolute绝对定位

(position:absolute),相对于父级,进行位置偏移,如果没有父级或者父级没有进行定位,则继续往上一级寻找参照物,直至最终的浏览器窗口
脱离了文档流。
限定条件: 定位基点(一般是父元素)不能是static定位,否则定位基点就会变成整个网页的根元素html

sticky

它会产生动态效果,
当元素在屏幕内,表现为relative,就要滚出显示器屏幕的时候,表现为fixed。
例如常见的 吸顶效果
tip:
父元素不可以有除了 overflow: visible 之外的值
因为改变了滚动容器,粘滞效果就会消失

查看评论