理解CSS(1) | 青训营笔记

47 阅读1分钟

这是我参与「第五届青训营 」伴学笔记创作活动的第 2 天

选择器

属性选择器

除了标签选择器、类选择器、id选择器、通配符选择器外,这里还讲了属性选择器

    <label>用户名:</label>
    <input value="vae" disabled>

    <label>密码:</label>
    <input value="123456" type="password">

    <style>
        [disabled] {
            background: #eee;
            color: #999;
        }
    </style>

上面的css代码表示只要这个元素有disabled的属性,就可以选中它

除此之外,还可以通过选择特定属性值来选择样式

    input[type="password"] {
            border-color: red;
            color: red;
        }

这里,只有input标签并且type值为password的才可以被选中

上面两个代码在浏览器中打开如下:

image.png

另外注意,这里并非必须等于某一个值才可以,也可以看属性值有什么规则,比如下面的代码

    <a href="#top">回到顶部</a>
    <a href="a.jpg">查看图片</a>

    <style>
        /* href以#开头 */
        a[href^="#"] {
            color: #aaa;
            padding-left: 1.1em;
            background: 0 center/1em url(https://assets/codepen.io/59477/arrow-up.png) no-repeat;
        }

        /* href以.jpg结尾 */
        a[href$=".jpg"] {
            color: #abc;
            padding-left: 1.2em;
            background: 0 center/1em url(https://assets/codepen.io/59477/image3.png) no-repeat;
        }
    </style>

image.png

伪类选择器

状态伪类

元素处于某一种特定的状态时,才会被选中

如a标签,会处于link(默认状态)、visited(访问过的状态)、hover(鼠标悬停的状态)、active(鼠标按下去后的状态)

使用方法 a:hover{}

结构性伪类

通过该元素在DOM树中的位置选中该元素

如first-child、last-child等

选择器的组合

.error{} 可以选中任意类是error的标签

但是,input.error{} 则只能选中类是error的input标签

选择器的组合有不同的方式,如下图

357EEC0B0DA84266958C6C06FAB24BBA.png

Tip:p标签中空格的显示可以使用white-space这个属性调节