css常用代码片段

80 阅读1分钟

触发BFC

  • overflow: hidden/auto/scroll

  • float: left/right

  • position:absolute/fixed

  • display: inline-block/table-cell/table-caption

  • html本身

3D变形

<div id="app">
  <div>
    <img src="https://img2.baidu.com/it/u=638285213,1746517464&fm=253&fmt=auto&app=120&f=JPEG?w=1422&h=800"/>
  </div>
</div>
#app{
  background: rgba(120, 143, 245, 0.3);
  /* 景深 */
  perspective: 3000px; 
}
#app div{
  background: rgba(120, 143, 245, 0.3);
  margin: 0 auto;
  transform-style: preserve-3d;
}

img{
  width: 500px;
  transition: all 0.5s;
}

#app div:hover img{
  transform: translate3d(200px, 50px, 400px);
}

高度塌陷解决方法

  • overflow: hidden

  • 设高度

  • 在所有浮动盒子下添加一个空盒子,并设置clear: both; height: 0

父盒子::after{
    content: '';
    clear: both;
    display: block;
    visibility: hidden;
}

动画

@keyframes name {
    from/0% { CSS样式 }
    percentage { CSS样式 }
    to/100% { CSS样式 }
}

例:animation: name .2s linear 1s infinite(循环) alternate(返回原点)
           (动画名称 动画所需时间 动画播放方式 动画开始时间 循环次数 播放方向)

省略号

  1. 固定宽:width
  2. 不换行:white-space: nowrap
  3. 溢出隐藏:overflow: hidden
  4. 省略号:text-overflow: ellipsis

垂直水平居中

position: absolute;
top: 50%;
left: 50%;
transform: translate(50%, -50%)
.box{
    display: flex;
    justify-content: center;
    align-items: center;
}
.box{ display: flex; }
.box div{ margin: auto; }
position: fixed;
top: calc(50% - 100px);
left: calc(50% - 100px);
<div>
    <img src='' />
    <span></span>
</div>

div{
    height: 200px;
    text-align: center;
}
img{
    vertical-align: center;
}
span{
    height: 100%;
    width: 0;
    display: inline-block;
    vertical-align: middle;
}
position: fixed;
top: 50%;
left: 50%;
margin-top: -高度的一半;
margin-left: -宽度的一半;
position: fixed;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;

使子盒子单行居中,多行靠左

.box{ display: flex; } 
.box div{ 
    margin: 0 auto; 
    text-align: left
}

不定宽导航水平居中

ul{ text-align: center }
li{ display: inline-block }

高度自适应

html, body{ height: 100% }

页面分为上中下三部分,上下部分固定高

<div id="app">
  <header></header>
  <main>
    <div>11111111</div>
    <div>11111111</div>
    <div>11111111</div>
  </main>
  <footer></footer>
</div>

#app{
  display: flex;
  flex-direction: column;
}

header, footer{
  height: 50px;
  background-color: darkgreen;
}

main{
  flex: 1;
  background-color: rgb(186, 220, 250);
}

image.png