派生选择器用的很多,派生选择器具体包括为后代选择器、子元素选择器、相邻兄弟选择器,我们来理解一下他们之间的具体用法与区别。
1、css后代选择器 <html> <head> <style type="text/css"> ul em {color:red; font-weight:bold;} </style> </head> <body> <ul> <li>List item 1 <ol> <li>List item 1-1</li> <li>List item 1-2</li> <li>List item 1-3 <ol> <li>List item 1-3-1</li> <li>List item <em>1-3-2</em></li> <li>List item 1-3-3</li> </ol> </li> <li>List item 1-4</li> </ol> </li> <li>List item 2</li> <li>List item 3</li> </ul> </body> </html> 运行结果:
即,无论你在哪里,我都要选中你,因为你是我的后代。
2、css子元素选择器 <style type="text/css"> h1 > strong {color:red;} </style> <h1>This is <strong>very</strong> <strong>very</strong> important.</h1> <h1>This is <em>really <strong>very</strong></em> important.</h1> 运行结果:
只有第一个h1会变色。
3、相邻兄弟选择器 <!DOCTYPE HTML> <html> <head> <style type="text/css"> li + li {color:red;} </style> </head> <body> <div> <ul> <li>List item 1</li> <li>List item 2</li> <li>List item 3</li> </ul> <ol> <li>List item 1</li> <li>List item 2</li> <li>List item 3</li> </ol> </div> </body> </html> 运行的结果是这样的:
|