读书笔记:《CSS世界》 - 张鑫旭 著

重新认识CSS,有一些最佳实践值得学习!

版次:2017 年 12 月第 1 版

  • CSS 这门语言本身并无逻辑可言,看重的是特性间的相互联系和具象能力。
  • 实际上,此时遇到的表现差异并不是浏览器的 bug,用计算机领域的专业术语描述应该是“未定义行为”(undefined behavior)。
  • 使用 content 属性,我们还可以让普通标签元素变成替换元素。
  • 可以借助 border-style: double 实现一些等宽的图形效果。例如,等比例“三道杠”图标效果。
  • 当没有指定 border-color 颜色值的时候,会使用当前元素的 color 计算值作为边框色。
  • ex 是 CSS 中的一个相对单位,指的是小写字母 x 的高度,没错,就是指 x-height。ex 的价值就在其副业上 - 不受字体和字号影响的内联元素的垂直居中对齐效果。
  • 如果使用数值作为 line-height 的属性值,那么所有的子元素继承的都是这个值;但是,如果使用百分比值或长度值作为属性值,那么所有的子元素继承的是最终的计算值。
  • float 属性有个著名的特性表现,就是会让父元素的高度塌陷;float 属性让父元素高度塌陷的原因就是为了实现文字环绕效果。
  • 元素设置了 overflow: hidden 声明,里面内容高度溢出的时候,滚动依然存在,仅仅滚动条不存在!
  • CSS 世界的渲染是一次渲染,是不会有死循环的。
  • 在 CSS 中,1em 的计算值等同于当前元素所在的 font-size 计算值,可以将其想象成当前元素中(如果有)汉字的高度。

最佳实践

大小不固定的弹框永远居中

<div class="container">
    <div class="dialog"></div>
</div>

.container {
    position: fixed;
    top: 0; right: 0; bottom: 0; left: 0;
    background-color: rgba(0, 0, 0, .5);
    text-align: center;
    font-size: 0;
    white-space: nowrap;
    overflow: auto;
}
.container:after {
    content: '';
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}
.dialog {
    display: inline-block;
    vertical-align: middle;
    text-align: left;
    font-size: 14px;
    white-space: normal;
}

display: table-cell 元素内连续英文字符换行

.word-break {
    display: table;
    width: 100%;
    table-layout: fixed;
    word-break: break-all;
}

页面滚动条不发生晃动

html {
    overflow-y: scroll; /* for IE8 */
}
:root {
    overflow-y: auto;
    overflow-x: hidden;
}
:root body {
    position: absolute;
}
body {
    width: 100vw;
    overflow: hidden;
}

单行文字溢出点点点效果

.ell {
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
}

利用绝对定位元素的流体特性和 margin: auto 的自动分配特性实现居中

.element {
    width: 300px; height: 200px;
    position: absolute;
    left: 0; right: 0; top: 0; bottom: 0;
    margin: auto;
}

SVG 矢量图标宽高

svg {
    width: 1em; height: 1em;
}

这样,无论图标是和大号文字混在一起还是和小号文字混在一起,都能和当前文字大小保持一致,既省时又省力。

整站通用的 :active 样式

a[href]:active,
button:active{
    background-image: linear-gradient(to top, rgba(0, 0, 0, .05), rgba(0, 0, 0, .05));
}

3 条评论

  1. reviewer
    rekt
    2018年7月30日

    Daddy you didn?t say wһat the best factor about God is.
    You havе to play too.

    回复
  2. reviewer
    link 188bet
    2018年7月28日

    Hey there just wanted to give you a brief heads up and let you
    know a few of the pictures aren't loading correctly. I'm not
    sure why but I think its a linking issue. I've tried it in two different browsers and both show the same outcome.

    回复
  3. reviewer
    188bet
    2018年7月28日

    It's a shame you don't have a donate button! I'd most
    certainly donate to this superb blog! I guess for now i'll
    settle for bookmarking and adding your RSS feed to my Google
    account. I look forward to new updates and will
    share this site with my Facebook group. Talk soon!

    回复

188bet进行回复 取消回复

您的电子邮箱地址不会被公开。