1、清除浮动
主要为子元素浮动(float)之后,父元素无法撑起高度和宽度。
-
<!-- html --><div class="clear"> <img src="demo.gif"></div>
-
<!-- css --><style> img { float: left; } /* 清除浮动 */ .clear::after { content: ""; display: block; clear: both; }</style>
2、文字少时居中,多时靠左
但是要注意,当p的内容为英文单词组成的时候,如果单词过长,而不是“ pppppppppppppppppppppppppppppp”这样的一次,会被视为一个单位而造成超过div的尺寸。
如果你想要英文字符也有中文字符的效果的话,在p使用“ word-break:break-all”。
-
<!-- html --><div class="box"> <p class="content"></p></div>
-
<!-- css --><style> .box { text-align: center; } .content { display: inline-block; text-align: left; }</style>
3、凹凸人
目的在于制造一个凹或凸的形状,利用了“ 2”。
-
<!-- html --><div class='ao'></div>
-
<!-- CSS --><style> .ao { display: inline-block; width: 0; } .ao::before { content: "love 你 love"; outline: 2px solid #000; color: #fff; }</style>
4、让padding,border不影响盒模型的大小
相信这点大部分人都知道,但是有一些奇怪的行为,比如说width <content + padding会怎样?实际上当padding + border> width时,元素的渲染大小(Chrome下)为padding + border;而padding + border <width时,允许剩余空间分配给content。
-
<!-- html --><div></div>
-
<!-- CSS --><style> div { box-sizing: border-box; }</style>
身高:100%占屏效果
-
<!-- html --><div></div>
-
<!-- CSS方法一 --><style> html,body { height: 100%; } div { height: 100% }</style><!-- CSS方法二 --><style> div { position: absolute; height: 100%; }</style>
5、任意高度元素展开
缺点是,如果高度太大会造成展开过快和重复中断,那么这个足够大的值应该适当。
-
<!-- html --><div></div>
-
<!-- CSS --><style> div { max-height: 0; overflow: hidden; transition: max-height .25s; } div.active { max-height: 666px; /* 需要足够大的值 */ }</style>
6、优雅的图片未加载或加载失败效果
需要注意的是,图片显示完成后,img会成为“替换元素”,而替换元素是无法设置伪元素的,因为内容被图片替换掉了;还需要注意attr里面的变量不能加双引号。
-
<!-- html --><div> <img src="demo.gif" alt="lululu"></div>
-
<!-- CSS --><style> div { width: 100px; height: 100px; overflow: hidden; } img { display: inline-block; width: 100%; height: 100%; position: relative; } img::after { /* 生成 alt 信息 */ content: attr(alt); /* 尺寸和定位 */ position: absolute; left: 0;bottom: 0;right: 0; /* 颜色 */ background-color: rgba(0,0,0,.5); /* alt 信息隐藏 */ transform: translateY(100%); /* 过渡动画效果 */ transition: transform .2s; } img:hover::after { /* alt 信息显示 */ transform: translateY(0); } </style>
7、CSS的悬浮图片替换效果
需要注意的是,如果快捷保存图片,保存的是src内的图片,而不是替换之后的。
-
<!-- html --><img src="demo.gif">
-
<!-- CSS --><style> img:hover { content: url(amazing.gif); }</style>
8、利于seo的“替换元素”标题logo
用h1的原因主要是因为SEO,语义化的问题。
-
<!-- html --><h1>Weismann's blog</h1>
-
<!-- CSS --><style> h1 { content: url(logo.gif); }</style>
9、高兼容,自动等宽,底部对齐的柱状图
需要注意的是,第一个i不能换行,换行后会产生后移的结果。
-
<!-- html --><div class="box"><i class="bar"></i> <i class="bar"></i> <i class="bar"></i> <i class="bar"></i></div>