CSS :scope-Pseudoklasse
Die CSS- :scope-Pseudoklasse repräsentiert das Referenzelement für Selektoren, wie das Root-Element in einem Shadow DOM oder das Element, das an querySelector() übergeben wird.
Sie wird häufig in JavaScript-DOM-Abfragen verwendet, um die Selektorenanpassung auf einen bestimmten Teilbaum zu beschränken. Beachten Sie, dass das veraltete Attribut <style scoped> in modernen Browsern nicht mehr unterstützt wird, :scope jedoch für DOM-Abfragen weiterhin relevant bleibt.
Version
Syntax
CSS :scope-Syntax
css
:scope {
css declarations;
}Beispiel für den :scope-Selektor:
CSS :scope-Codebeispiel
html
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
.container {
margin: 40px auto;
max-width: 700px;
background-color: #eeeeee;
padding: 20px;
box-shadow: 0 0 4px rgba(0, 0, 0, 0.25);
}
section {
padding: 30px;
}
</style>
</head>
<body>
<h2>:scope selector example</h2>
<div class="container">
<section>
<p>
Inside the scope.
</p>
</section>
</div>
<script>
const container = document.querySelector('.container');
const scopeElement = container.querySelector(':scope > section');
scopeElement.style.backgroundColor = '#1c87c9';
scopeElement.style.color = '#fff';
</script>
</body>
</html>Practice
Worauf bezieht sich der Scope in CSS?