使用 CSS 選擇子元素
CSS 子元素組合器用於選擇父元素的所有子元素。CSS 子代元素組合器用於選擇父元素的所有子代元素
子元素組合器
CSS 子元素組合器用於選擇父元素的所有子元素。CSS 子元素組合器的語法如下。> 介於兩個選擇器之間 −
Selector > Selector {
attribute: /*value*/
}
示例
以下示例說明了 CSS 子元素組合器 −
<!DOCTYPE html>
<html>
<head>
<style>
article > p {
color: black;
background-color: orange;
}
</style>
</head>
<body>
<article>
<h2>Demo Heading</h2>
<p>Duis consequat aliquet leo, quis aliquam ex vehicula in. Vivamus placerat tincidunt hendrerit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque semper ex eget nulla consectetur varius.</p>
</article>
<p>This is demo text.</p>
<div>
<p>This is another demo text.</p>
</div>
</body>
</html>
子代元素組合器
CSS 子代元素組合器用於選擇父元素的所有子代元素
CSS 子代元素組合器的語法如下 −
Selector Selector {
attribute: /*value*/
}
如果要選擇元素內的元素,則使用 element element 組合器 −
article p
示例
讓我們看一個示例 −
<!DOCTYPE html>
<html>
<head>
<style>
article p {
text-align: center;
border: 10px groove tomato;
}
</style>
</head>
<body>
<article>
<h2>Demo Heading</h2>
<p>This is another demo text. </p>
</article>
<p>This is demo text.</p>
</body>
</html>
第 n 個子元素
對作為其父元素第 n 個子元素的元素設定樣式。例如,為 .child div 的第一個子元素設定背景顏色 −
.child:nth-child(1){
background-color: #FF8A00;
}
為 .child div 的第二個子元素設定背景顏色 −
.child:nth-child(2){
background-color: #F44336;
}
示例
讓我們看一個示例 −
<!DOCTYPE html>
<html>
<head>
<style>
form {
width:70%;
margin: 0 auto;
text-align: center;
}
* {
padding: 2px;
margin:5px;
box-sizing: border-box;
}
input[type="button"] {
border-radius: 10px;
}
.child{
display: inline-block;
height: 40px;
width: 40px;
color: white;
border: 4px solid black;
}
.child:nth-child(1){
background-color: #FF8A00;
}
.child:nth-child(2){
background-color: #F44336;
}
.child:nth-child(3){
background-color: #C303C3;
}
.child:nth-child(4){
background-color: #4CAF50;
}
.child:nth-child(5){
background-color: #03A9F4;
}
.child:nth-child(6){
background-color: #FEDC11;
}
</style>
</head>
<body>
<form>
<fieldset>
<legend>CSS Pseudo Classes and CSS Classes</legend>
<div id="container">
<div class="child"></div><div class="child"></div><div class="child"></div><div class="child"></div><div class="child"></div><div class="child"></div>
</div><br>
</body>
</html>
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP