3

I have a page that contains several divs with the classname row.

<section>
    <div class="row"> [...] </div>
    <div class="row"> [...] </div>
    <div class="row"> [...] </div>
</section>

I want to target the first of these so that I can apply certain spacing to them.

section div:nth-of-type(1) {
    margin-top: 10px;
}

However, in some cases, the div I want to affect is not actually the first div in the section. It's the first div after a div that contains a noscript tag.

How can I ensure I am targeting the correct div in this case? And are there better approaches?

Alexis
  • 5,681
  • 1
  • 27
  • 44
alanbuchanan
  • 3,993
  • 7
  • 41
  • 64
  • 1
    *after a div that contains a noscript tag* - It is better you add some class to that `div` which contains the noscript tag. Without that this would be tough (impossible I think) with pure CSS because you can select a sibling or descendant with CSS but not sibling of the parent or parent. – Harry May 04 '16 at 12:40
  • I dont think this can be done with pure CSS... Jquery will save you.. – Rajshekar Reddy May 04 '16 at 12:51
  • It's not possible in CSS because there is no parent selector. So you can't dive into a div element to see whether it contains a noscript tag and then go back and select the next sibling element. – Chris May 04 '16 at 12:52

3 Answers3

1

Using CSS you cannot select an element based on its children (exsistent or not).

With jQuery, you can try something like:

$('div.row:not(:has(noscript))').css('margin-top', '10px');
Linuslabo
  • 1,568
  • 2
  • 24
  • 34
0

If you use nth-of-type or first-of-type here type means <div> of <p> etc. It will not work if you use class selector because the type remains same.

For Example

<p>hello</p>
<div class="row">hello</div>

In above code if you use div:nth-of-type(1) then it will catch <div class="row">hello</div> because its first div.

Example : https://jsfiddle.net/czv0z93t/

But

<div class="first">Hello</div>
<div class="row">Hello</div>

In above code if you use .row:nth-of-type(1) it will not work because its previous element type is also div.

So here you can simply use .row:nth-child(2).

Example : https://jsfiddle.net/czv0z93t/1/

Gaurav Aggarwal
  • 9,809
  • 6
  • 36
  • 74
0

I would just have a much easier life and assign a class to all the ones which you want to have special styling like <div class='row no-top-border'>

Though you can definitely experiment with div.row > div[noscript], div.row:first-child {}

Zargold
  • 1,892
  • 18
  • 24