The sibling of CSS selectors selectors (~ and +)

  Today, when I changed the style of the webpage written by others, I came across this selector, '~', I was dumbfounded at the time, and couldn't tell the difference between '+' and '~', although I knew them Both are sibling selectors.

  Later, I checked it online, maybe the way I searched was wrong, and I didn't find the answer I wanted, so I took these two selectors to test it privately. Found it to be so.

  Let's talk about the code first:

  (1), '~' selector

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
		.h3 ~ p{
			color: red;
		}
	</style>
</head>
<body>
	<p>This is a paragraph tag</p>
	<p>This is a paragraph tag</p>
	<p>This is a paragraph tag</p>
	<h3 class="h3">This is the title tag</h3>
	<p>This is a paragraph tag</p>
	<p>This is a paragraph tag</p>
	<p>This is a paragraph tag</p>
	<h3>This is the title tag</h3>
	<p>This is a paragraph tag</p>
	<p>This is a paragraph tag</p>
	<p>This is a paragraph tag</p>
</body>
</html>

  The effect is as follows:

        

 

  (2), '+' selector

  

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
		.h3 + p{
			color: red;
		}
	</style>
</head>
<body>
	<p>This is a paragraph tag</p>
	<p>This is a paragraph tag</p>
	<p>This is a paragraph tag</p>
	<h3 class="h3">This is the title tag</h3>
	<p>This is a paragraph tag</p>
	<p>This is a paragraph tag</p>
	<p>This is a paragraph tag</p>
	<h3>This is the title tag</h3>
	<p>This is a paragraph tag</p>
	<p>This is a paragraph tag</p>
	<p>This is a paragraph tag</p>
</body>
</html>

  The code is still the same, just replace the '~' with a '+', the result is very different.

      

 

    Through these two examples, it can be found that although these two selectors represent sibling selectors, the '+' selector means that the adjacent sibling elements after an element, that is, next to each other, are single. The '~' selector represents all the specified elements of the same level after an element, emphasizing all.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325225210&siteId=291194637