Metzed
Metzed

Reputation: 491

How do I style a div but only if it has an H1 as its first child?

Is there a way that I can add text-align:center to all div.wpb_wrapper which have h1 as the first child? One of the reasons I need this is that there are multiple div.wpb_wrapper that have the same parent, but not all have <h1> as the first child.

In the example below I only want to style the second div.

<div class="wpb_wrapper">
   <h2>Other text</h2>
   <p>Other text</p>   
</div>
<div class="wpb_wrapper">
   <h1>Text</h1>
   <h2>Other text</h2>
   <p>Other text</p>   
</div>

EDIT: I can't apply text-align center to h1 because it is has display: inline-block; already applied. That's why I need to style the parent.

Upvotes: 1

Views: 1089

Answers (2)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167212

You cannot access the parent in CSS as of now. But you can do something like this:

Alternate Solution

As there's no CSS Parent Selector, we can apply text-align: center for all the elements that are siblings and the <h1> itself this way:

.wpb_wrapper > h1:first-child,
.wpb_wrapper > h1:first-child ~ * {
  text-align: center;
}

This will apply text-align: center to all the siblings. This way, the <h2> and <p> tags will be aligned center.

Let's try here:

.wpb_wrapper > h1:first-child,
.wpb_wrapper > h1:first-child ~ * {
  text-align: center;
}
<div class="wpb_wrapper">
   <h2>Other text</h2>
   <p>Other text</p>   
</div>
<div class="wpb_wrapper">
   <h1>Text</h1>
   <h2>Other text</h2>
   <p>Other text</p>   
</div>

According to the OP:

I want to style the second div only. I do not want to center the text in the first div. I only want to center text in the div when it has an H1 as the first child. And I can't apply text-align center to h1 because it is has display: inline-block;.

So the only way would be:

.wpb_wrapper > h1:first-child ~ * {
  text-align: center;
}

Or using JavaScript or jQuery and using the .closest() this way:

$(".wbp-wrapper > h1:first-child").each(function() {
    $(this).closest(".wbp-wrapper").css("text-align", "center");
});

Upvotes: 4

beerwin
beerwin

Reputation: 10327

Unfortunately you can't do that with CSS only.

If you are already using jQuery you could do this:

Javascript:

$('.wbp-wrapper > h1:first-child').each(function(){
    $(this).closest('.wbp-wrapper').addClass('centered');
});

CSS:

.centered {
    text-align: center;
}

Upvotes: 0

Related Questions