1. 程式人生 > >CSS 常用的幾種選擇器

CSS 常用的幾種選擇器

1、基本選擇器

元素選擇器

<html>
<head>
<meta charset="UTF-8">
<title>元素選擇器</title>
    <style type="text/css">
        span{color:red;font-size: 20px}
    </style>
</head>
<body>
    <span>hello</span><br/>
    <span>world</span>
</body
>
</html>

執行效果:
這裡寫圖片描述

id選擇器

<html>
<head>
<meta charset="UTF-8">
<title>id選擇器</title>

<style type="text/css">
    #div1{background-color: red}
    #div2{background-color: pink}
</style>

</head>
<body>
    <div id = "div1">hello world1</div
>
<div id = "div1">hello world1</div> <div id = "div2">hello world2</div> </body> </html>

執行結果:
這裡寫圖片描述
class選擇器

<html>
<head>
<meta charset="UTF-8">
<title>class選擇器</title>

<style type="text/css">
    .style1{background-color
: red
} .style2{background-color: pink}
</style> </head> <body> <div class = "style1">div1</div> <div class = "style1">div2</div> <div class = "style2">div3</div> </body> </html>

執行結果:
這裡寫圖片描述

基本選擇器的優先順序:

id > class > 元素

2、屬性選擇器

格式:基本選擇器[屬性 = ‘屬性值’]{ }

<html>
<head>
<meta charset="UTF-8">
<title>屬性選擇器</title>
<style type="text/css">
    input[type = 'text'] {background-color: red}
    input[type = 'password'] {background-color: pink}
</style>
</head>
<body>
    <form>
        name:<input type = "text"><br/>
        pass:<input type = "password">
    </form>

</body>
</html>

執行結果:
這裡寫圖片描述

3、偽類選擇器

<html>
<head>
<meta charset="UTF-8">
<title>偽類選擇器</title>
    <style type="text/css">
        a:link{color:green ;font-size: 50px}
        a:hover{color:pink;font-size: 50px}
        a:active{color:yellow;font-size: 50px}
        a:visited{color:red;font-size: 50px}
    </style>
</head>
<body>
    <a href = "#">點選</a>

</body>
</html>

效果:
開啟網頁時標籤為綠色
將滑鼠放在標籤上時標籤為粉色
點選標籤是標籤為黃色
點選後標籤為紅色

4、層級選擇器

<html>
<head>
<meta charset="UTF-8">
<title>層級選擇器</title>
    <style type="text/css">
        #d1 .dd2 span{color:red}
    </style>
</head>
<body>
    <div id = "d1">
        <div class = "dd1">
            <span>span1-1</span>
        </div>
        <div class = "dd2">
            <span>span1-2</span>
        </div>

    </div>
    <div id = "d2">
        <div class = "dd1">
            <span>span2-1</span>
        </div>
        <div clss = "dd2">
            <span>span2-2</span>
        </div>

    </div>

</body>
</html>

執行結果:
這裡寫圖片描述