In this tutorial we will walk through a few cases where having a CSS parent selector might come in handy, along with some possible workarounds. Let’s get started!
Wait, What’s a Parent Selector?
CSS selectors allow us to target elements, moving down and across the DOM tree, getting more specific as we do so. Here’s an example of the kind of selector you might find in Bootstrap–it travels down the DOM tree from the nav.navbar-dark element, to the ul, the li, then finally the a.nav-link.
- .navbar-dark .navbar-nav .nav-item .nav-link {
- }
- .nav-link::parent {
- }
Case 1: Styling Legacy Content
Styling legacy content, with dated markup and structure, is a classic challenge when redesigning a website. Before HTML5, for example, an image might typically have been wrapped with a p, div, or sometimes with a span along with a nested p used to wrap the image caption. There was no standard way to wrap an image and caption. Later, we adopted the figure and figcaption elements, making our document structure more semantic.
![]() |
- .page-content div {
- padding: 15px;
- background-color: #f3f3f3;
- margin: 10px 0 20px;
- }
- .page-content div img {
- marging: 0 0 10px;
- }
- .page-content div .img-caption {
- color: #999;
- font-size: 12px;
- text-align: center;
- Wisplay: block;
- }
Case 2: Maintaining Video Ratio
Another example looks at maintaining embedded video (like from Youtube or Vimeo) ratio, as well as making the video fluid. These days, largely thanks to the investigative work by Dave Rupert and pals, it’s widely accepted that the best approach is to apply padding-top or padding-bottom to the parent element.
![]() |
Code snippet from CSS-Tricks: Fluid width video |
Therefore, declaring the styles as follows is again impractical since it will impact all the divs within the .page-content including ones which don’t contain an embedded video.
- .page-content {
- width: 560px;
- margin-right: auto;
- margin-left: auto;
- margin-top: 30px;
- }
- .page-content div {
- position: relative;
- padding-bottom: 56.25%;
- }
- .page-content div iframe {
- position: absolute;
- top: 0;
- width: 100%;
- height: 100%;
- }
Case 3: Responding to Form Input
In this example we have a form with several inputs. When we focus on one of the inputs, it is given a more prominent border color, highlighting the user’s position within the form.
Sometimes you also may come across the situation where not only the border color, but the element wrapping the input is highlighted, making the input even more prominent:
![]() |
Input form focus. |
Written by Thoriq Firdaus
If you found this post interesting, follow and support us.
Suggest for you:
CSS: Foundation classes on CSS
Coding Made Easy: HTML & CSS For Beginners
Bootstrap 4 Rapid web development framework HTML CSS JS
No comments:
Post a Comment