[英]HTML different Styles for two sections
我想知道天氣有一種方法可以將兩種不同的樣式添加到 HTML 中的兩個代碼塊中。 例如,我有兩個部分
<section>
<header class="major">
<h2>Section 1</h2>
</header>
</section>
和
<section>
<header class="major">
<h2>Section 2</h2>
</header>
</section>
我想為以上兩個部分應用兩種不同的樣式。
請讓我知道是否有辦法做到這一點。
我會為您的每個部分添加一個類或 ID - 這正是它們的用途。
/* Our base styles*/ section { border: dashed 1px black; padding: 1em; margin: 1em; font-weight: bold; color: #900; } /*Can over ride styles with classes*/ section.type-a { background-color: #fee; border: solid 4px red; } section.type-b { background-color: #efe; color: #060; }
<section class="type-a"> <header class="major"> <h2>Section 1</h2> </header> </section> <section class="type-b"> <header class="major"> <h2>Section 2</h2> </header> </section>
我希望我現在得到了你的問題。 所以,你可以做什么,你可以將你的表格模板添加到另一個 div 中,並給它一個 class 。 現在,您可以定義一個樣式為您的section
和另一section
是在類中second-template
。 這樣,您可以為相同的樣式制作不同的樣式。
現在對於腳本,我已經編寫了一段示例代碼。 您可以相應地更改相同的內容。
$('.second-template').find('section').css("color", "green");
像這樣嘗試:
$('.second-template').find('section').css("color", "green");
section { background: red; } .second-template > section { background: blue; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <section> <header class="major"> <h2>Section 1</h2> </header> </section> <div class="second-template"> /*Include your secoond template here */ <section> <header class="major"> <h2>Section 1</h2> </header> </section> </div>
您可以使用nth-of-type()
選擇器:
section:nth-of-type(index){
//Your rules
}
例子:
section:nth-of-type(1){ color: green; } section:nth-of-type(2){ color: red; }
<section> <header class="major"> <h2>Section 1</h2> </header> </section> <section> <header class="major"> <h2>Section 2</h2> </header> </section>
使用 CSS3 :nth-child() 選擇器,如下所示
section:nth-child(1) {
//apply your changes to the first section
}
section:nth-child(2) {
//apply your changes to the second section
}
如果需要到達不同的類,則需要按如下所示遍歷元素。 但關鍵是使用 nth-child 選擇器引用第一個元素,我認為不需要打擾腳本,下面的代碼適用於我並將不同的樣式應用於不同的元素。
<style type="text/css">
section:nth-child(1) .major{
background:red;
height:100px;
color:#fff;
}
section:nth-child(2) .major{
background:blue;
height:100px;
color:lightcyan;
}
</style>
<section>
<header class="major">
<h2>Section 1</h2>
</header>
</section>
<section>
<header class="major">
<h2>Section 2</h2>
</header>
</section>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.