-1

I want to address the first appearance of an element on the website. Independent of child situation. So let's say the first h2 appearance, no matter where it sits, to remove the top padding there while the following have one. Or even better if it would work with classes, like catching the first .entry-title of the page. As said, the elements might be embraced by many other unforeseen elements, so any selector addressing children or siblings is not helpful. I found some older answers saying it is not possible at all, others giving workarounds for specific situations, but I wonder if meanwhile, 2016, such a modality exists?

Thanks for any hint Sofian

cdlane
  • 40,441
  • 5
  • 32
  • 81
Sofian
  • 41
  • 4
  • Have a look at BoltClock's answer here - http://stackoverflow.com/questions/2717480/css-selector-for-first-element-with-class?rq=1. Thing to note is, that approach would still select the first element with the class under each parent and not only the first in the whole page. – Harry Mar 18 '16 at 12:28
  • You could use h2:first-of-type, this would only select the first h2 on the page – DavidB Mar 18 '16 at 12:28
  • 1
    @DavidB - `:first-of-type`, like all `nth-child` pseudos, operators with reference to an element's position in relation to its siblings, not the whole document. – Mitya Mar 18 '16 at 12:29

4 Answers4

1

Please

$("h2:first").css("padding", "0");
0

You can't do this with pure CSS but you could use jQuery.

$( "h2:first" ).css( "padding", "0" );
Aaron
  • 10,187
  • 3
  • 23
  • 39
0

For a non-jQuery alternative:

const firstH2 = document.querySelector('h2');
if (firstH2) firstH2.style.padding = '0';
Nathan
  • 325
  • 1
  • 2
  • 10
0

I think you cannot do it with css, but it is easy to do in JavaScript.

first_h2  = document.querySelectorAll('h2')[0];
Claudio King
  • 1,606
  • 1
  • 10
  • 12