CSS series next generation selector, sub selector and adjacent sibling selector

  • The descendant selector has a larger range than the child selector, including the child selector and the child selector. The descendant selector uses the space symbol interval selector.
  • Child selector: the child selector is only the first level child element of the parent selector. Use the ">" symbol to link the selector.
  • Adjacent sibling selector, which has the same parent element and two adjacent elements, uses "+" symbolic link

1. Descendant selector

  • For example, the following html code, em is the descendant element of h1, and the following css style will only affect the content of the em tag in h1 to turn red, and will not affect the content of em in p.

css:

h1 em {color:red;}

 HTML:

<html>
<head>
<style type="text/css">
h1 em {color:red;}
</style>
</head>
<body>
<h1>This is a <em>important</em> heading</h1>
<p>This is a <em>important</em> paragraph.</p>
</body>
</html>

Operation result:

  • The writing of h1 em is applicable to all em in h1, no matter how many layers EM is nested.
<h1>This is a <span><p><em>important</em></p></span> heading</h1>

Run results:

2. Sub selector

Set the content of the strong label of the child element of h1 as red.

In the second h1, because the parent element of strong is not h1, but em, the settings in css will not work on it

css:

h1 > strong {color:red;}

HTML:

<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
h1 > strong {color:red;}
</style>
</head>

<body>
<h1>This is <strong>very</strong> <strong>very</strong> important.</h1>
<h1>This is <em>really <strong>very</strong></em> important.</h1>
</body>
</html>

 

Operation result:

3. Adjacent brother selector

h1 and p have the same parent element body, and the adjacent sibling selector needs to be next to each other, and only applies to the content of the p tag adjacent to h1.

css:

h1 + p {margin-top:50px;}

HTML:

<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
h1 + p {margin-top:50px;}
</style>
</head>

<body>
<h1>This is a heading.</h1>
<p>This is paragraph.</p>
<p>This is paragraph.</p>
<p>This is paragraph.</p>
<p>This is paragraph.</p>
<p>This is paragraph.</p>
</body>
</html>

 

Operation result:

Remember that you can only select the second element of two adjacent siblings with a single binder

So h1+p will only act on the first p, as shown in the following example:

It only works for the second and subsequent li of the two lists, but not for the first Li.

css:

li + li {font-weight:bold;}

HTML:

<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
li + li {font-weight:bold;}
</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>

 

Operation result:

 

Routine source:

Tags: PHP

Posted on Fri, 01 Nov 2019 15:21:05 -0700 by jwer78