1. 程式人生 > >前端入門學習筆記(十四)CSS基礎(二)CSS 規則與選擇器

前端入門學習筆記(十四)CSS基礎(二)CSS 規則與選擇器

CSS語法

CSS是由瀏覽器解釋的樣式規則,然後應用於文件中相應的元素。 樣式規則有三個部分:選擇器,屬性和值。 例如,標題顏色可以定義為:

        h1{color: red;}  
        選擇器{ 屬性: 值;}
        selector{property:value;}

需要設定多個屬性的時候,可用分號將其分隔開,如

h1{
	color: red;
	background: gray;
}

再用webstorm進行編寫時,顏色會在側邊欄顯示出來

在這裡插入圖片描述

型別選擇器

例如要定位全部的段落(CSS宣告全以分號結尾,宣告組由大括號結尾)

        p {
            color: red;
            font-size:130%;
        }

id和class選擇器

id選擇器允許您設定具有id屬性的HTML元素,而不管它們在文件樹中的位置。 這裡是一個id選擇器的例子:

使用“#”符號,後跟ID名

CSS部分
 #idSelect {
	color: white;
	background: gray;
}
HTML部分
<div id="idSelect">
    <p> div 會用於標記區域、標記HTML文件的各部分</p>
</div>
<p> 在div內的型別會受到影響</p>

程式碼效果在這裡插入圖片描述

class選擇器以類似的方式工作。 主要區別在於id只能每頁應用一次,而class可以在頁面上多次使用。 並且CSS部分略有寫不同:

使用"."符號,後跟類名

.cssSelect{
    color: white;
    background: gray;
}
<html>
<head>
    <style>
        .cssSelcet {
            color: white;
            background: gray;
        }
    </style>
</head>
<body>
<div>
    <p class="cssSelcet">class可以</p>
    <p>class可以 </p>
</div>
<p class="cssSelcet"> 在頁面中多次使用</p>
<p>在頁面中多次使用 </p>
</body>
</html>

程式碼效果 在這裡插入圖片描述

後代選擇器

選擇另一個元素的後代的元素如示例程式碼中,要選擇“intro”的“first”中的“emFirst”以及“emSecond”

<html>
<head>
    <style>
        #intro p {
            color: pink;
            background-color: black;
        }

        #intro .first em-first {
            /*css程式碼命名多為-,非駝峰或_命名*/
            /*em 為 Emphasized text(強調文字的縮寫)*/
            color: white;
            background-color: gray;
        }

        #intro .first em-second {
            color: gray;
            background-color: pink;
        }
    </style>
</head>
<body>
<div id="intro"><!--id 為父元素屬性,子元素才可使用first屬性 -->
    <p class="first">div父元素內,first內
        <em-frist>emFirst內</em-frist>
        <em-second>emSecond內</em-second>
    </p>
    <p class="first">div父元素內,first內,無em</p>
</div>
<p class="first">div元素外,first內,<em>em內</em></p>
<p class="first">div元素外,first內,無em</p>
</body>
</html>

程式碼效果如下 在這裡插入圖片描述