HTML5: How to specify that the styles only apply to this element's parent element and that element's child elements?
Solution:
HTML Code:
Explanation:
- This HTML code defines a webpage with two sections, each containing a heading and a paragraph.
- Inside the <head> section, a global CSS style block is defined to set default styles for all <h1> and <p> elements.
- Within the first <div> element, another CSS style block is defined with the scoped attribute, indicating that the contained styles only apply to elements within the scope of the parent element (the <div>) and its child elements.
- Inside the scoped CSS style block, specific styles are defined for <h1> and <p> elements within the <div>, overriding the global styles.
- As a result, the heading and paragraph within the <div> will have blue and green colors, respectively, while the heading and paragraph outside the <div> will retain the default colors specified in the global CSS style block.
Live Demo:
See the solution in the browser
Supported browser
![]() |
![]() |
![]() |
![]() |
![]() |
Yes | Yes | Yes | Yes | Yes |
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.