相邻选择器:首先要知道浏览器的一个特性,他是从上向下执行的。只选中他的兄弟类,所以也叫兄弟选择器。
方式1:类名1 + 类名2{ } 只能选中类名2
方式2:类名1 ~ div { } 除了类名1不会选中,他所有兄弟类都会被选中。
方式1:选中类b
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>相邻选择器</title> <style> div{ width: 400px; height: 50px; margin: 20px; background: white; border: 1px solid black; } .a + div{ background: #000000; //这里也可以这样写 :.a + .b //.a + .c 也可以选中类c } </style> </head> <body> <div class="a">a</div> <div class="b">b</div> <div class="c">c</div> </body> </html>
方式二:选中类a的所有兄弟类
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>相邻选择器</title> <style> div{ width: 400px; height: 50px; margin: 20px; background: white; border: 1px solid black; } .a ~ div{ background: #000000; //当然也可以这样写.a ~.c {} 它就只会选中类c。 } </style> </head> <body> <div class="a">a</div> <div class="b">b</div> <div class="c">c</div> </body> </html>