直下の要素のみスタイル指定する方法 HTML5/CSS3
直下の要素のみスタイル指定する方法
たまに使いどころが出てくる「直下の要素のみスタイル指定」したいケースへの対応です。
「idがparentの要素」の直下である「div要素」のみ背景色をつけています。
#parent > div { background-color:#4CAF50; }
全体のソースはこんな感じです。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <style> div,p { background-color:white; margin: 2px; border: 1px solid; height: 4rem; width: 4rem; } #parent { border: 1px solid; height: 20rem; width: 20rem; } #parent > div { background-color:#4CAF50; } .children{ height: 2rem; width: 2rem; } </style> </head> <body> <div id="parent"> <div> <div class="children"></div> </div> <div> <div class="children"></div> </div> <div> <div class="children"></div> </div> <p></p> </div> </body> </html>