Tips on choosing the initial h4 element within the same parent element but at different levels of depth

Consider the following code snippet:

<div class="main-element">
    <h4>Title 1</h4>
    <ul>
        <li></li>
        <li></li>
        <li>
            <h4>Title2</h4>
        </li>
    </ul>
</div>

The goal is to apply the same styling to all h4 elements, while adding additional styles to the first one. Specifically, the margin-top and margin-bottom for all h4 elements should be 8px, except for the first h4 element which should have a margin-top of 0.

Attempts were made using :first-child and first-of-type selectors, as shown below:

.main-element h4 {
  color: blue;
}

.main-element h4:first-of-type {
  color: red;
}

However, this resulted in all h4 elements being colored red, rather than just the first one.

Answer №1

first-of-type will evaluate to true for both instances of h4 because the second one is nested within an <li>, which resets the count back to the first child.

It may be helpful to assign unique classes to the elements you want to style individually.

.main-element .reset {
  margin-top: 0px;
  color: red;
}

.main-element h4 {
  margin-top: 8px;
  margin-bottom: 8px;
  color: blue;
}
<div class="main-element">
    <h4 class='reset'>Title 1</h4>
    <ul>
        <li></li>
        <li></li>
        <li>
            <h4>Title2</h4>
        </li>
    </ul>
</div>

Answer №2

first-of-type refers to the first occurrence of a specific type within its parent container. Therefore, the selector .main-element h4:first-of-type targets the first h4 element that is a descendant of main-element.

If you only want to style the first h4 element that is a direct child of its parent, you can use the ">" selector, like so:

.main-element > h4:first-of-type {
  color: red;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Position the final offspring adjacent to the one that came before it using Flexbox

I am trying to figure out how to position the last child (CVV) next to the previous one (Expiry), so they are on the same row: .form-col-1--cc { display: flex; flex: 30%; flex-direction: column; text-align: right; align-items: flex-end; } < ...

Rotating Tetris pieces around an axis using HTML5 Canvas

I am currently working on a project and I have encountered a problem. When you press the UP key and hold it down, you will see what I mean: My goal is to make the object rotate around its axis instead of its current behavior. Please take a look at the co ...

Slick Slider fails to load on web browsers

Hi everyone, I have a snippet of HTML code that I need help with: <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/jquery.slick/1.6.0/slick.css"/> </head> <body> ...

How can I troubleshoot the overflow-y problem in a tab modal from w3 school?

https://www.example.com/code-sample overflow: scroll; overflow-y: scroll; When I type a lot of words, they become hidden so I need to use overflow-y=scroll. Despite trying both overflow: scroll; and overflow-y: scroll;, I have been unable to achieve the ...

Incorporate a linked select dropdown into the registration form

I am working on a sign-up form and trying to integrate 2 linked select boxes into the form. The code for the linked select boxes works fine separately but when I attempt to add it to the form, it doesn't display as expected. I attempted to incorporate ...

Modifying the border hue of Material-UI's Select Component

Here is the Select component I've created using materials-UI <FormControl variant="outlined"> <Select value={this.state.value} onChange = {this.handleChange} className={this.props.classes.select} inputProps = {{class ...

What impact do media queries have on scaling web pages?

Why does the page scale change with media queries? @media only screen and (min-width: 500px) { body { background-color: blue; } } @media only screen and (min-width: 800px) { body { background-color: green; } } @media only screen and (min-width: 1000px) ...

I am interested in creating a design where two DIVs are layered on top of each other with one having transparency, allowing visibility through to the background DIV. This can be achieved using a combination of

Looking to enhance the visual appeal of my website, I decided to incorporate a background image within a div. To add more depth and creativity, I am now striving to overlay a semi-transparent black box on top of the image. This overlay will not only allo ...

WebSocket Binary in Chrome version 16

I'm encountering issues while setting up a WebSocket server in node.js. After seeking help on stackoverflow, I managed to find a piece of code to use for the server. Here is the current server code: var net = require("net"), crypto = require("crypto" ...

Error: The function explore() is missing a required parameter called 'path'

Here is my code snippet: def navigate(directory): # To avoid issues with forward slashes, normalize the path directory = os.path.normpath(directory) if os.path.isdir(directory): subprocess.run([FILEBROWSER_PATH, directory]) elif os.path.isfile(directo ...

Styling Scrollbars in Datatables

I need assistance on styling a specific datatable scrollbar using Webkit. Below is the code snippet: id ::-webkit-scrollbar-track { background-color: transparent; border-radius: 5px; } id::-webkit-scrollbar { width: 13px; } ...

Unexpected Visual Basic Web Label Formatting

I am facing an issue with the styling of a complex label. The CSS code doesn't always apply as expected. Interestingly, when I ran this code on two different machines, the styles were inconsistent. The code seems messy and disorganized to me, but al ...

When the data-toggle="table" attribute is utilized, the content will be shown as plain text within the <td> element

While incorporating bootstrap data-toggle="table", an issue arises wherein it converts content within <td> into plain text disregarding any tags. https://i.sstatic.net/nuTLY.png The code snippet in question is as follows <!DOCTYPE html ...

Selecting the label "for" will activate both the anchor tag and input tag simultaneously

It seems like I'm having trouble making this work, and it appears to not be possible. That's why I'm reaching out for help... Here is the CSS that is being used: label.btn { cursor:pointer; display:inline-block; } label.btn>inpu ...

What is causing the variables in my HTML tags to not appear?

I am currently working on a component to display random products from an array. Despite being able to see the attributes like props.products[random].company when I console log them, they are not rendering properly when placed inside HTML tags. Although th ...

Link embedded in prism formatting, encased in code snippet

In the HTML template, I have the following code snippet: <pre> <code class="language-markup"> {% filter force_escape %} <Item> <MarkUp><a href="http://google.com">Google</a></MarkUp> <No ...

JavaScript - Sending Form Data with Local Time

I want to automatically submit a form at a specific time of day The form should be submitted every day at "15:30:00" Here is the JavaScript code I have written: <script type="text/javascript> function initClock() { var now = new Date(); var h ...

Modify the bootstrap form dynamically in response to the user's input. Update the form layout instantly as the user types, with no need for clicking any buttons

Imagine a scenario where, as soon as you enter your credit card number, the form automatically undergoes a change without requiring a button click, similar to how a credit card logo pops up. The form detects changes instantly after the input field has be ...

Do you need the Tooltip Module for Angular-bootstrap popover to work properly?

"Could it be possible that my popover isn't working because it requires the tooltip module just like the Bootstrap jQuery plugin?" Is this the reason my popover isn't functioning as expected? What exactly is the tooltip module and do I need to i ...

Remove any javascript code from the ajax modal when it is closed or hidden

I am in the process of creating a music website that showcases songs along with their lyrics. One of the features I have added is a lyrics button that, when clicked while a song is playing, opens up a modal displaying the live lyrics. Everything works per ...