How to make H1, H2, etc as links?

Im a little embarassed to be asking a question in this section as I consider myself a competent HTML coder!

However I’m stumped on this one.
What is the ‘correct’ code for turning a h1, h2 etc heading into a link?

Is it:
<a href=“#”><h1>heading</h1></a>


<h1><a href=“#”>heading</a></h1>

Which nesting is correct?
I know both of them work, just not sure which is right. I have been putting the <a> tag on the outside.

And what is the correct way to style this in CSS? My h1 style is automatically overwritten when I turn it into a link.

Is it:
h1 a:link

The second. The A element is an inline element and can’t contain block elements. The Hx elements are all block elements and can contain inline elements.

To be sure, try them both and throw tham at the validator.

While the validator will catch the first as invalid in this case, the validator doesn’t always tell the truth about what is conforming HTML. The validator only checks SGML-validity against the DTD (that the document declares itself), and the HTML spec has requirements beond that.

I believe it is the second one as well.

Yes I thought being a block element, H1 would require the a tag to be contained within it.
Im not too fussed on validation, Im more concerned at how the CSS would treat it.

You can’t be sure how the DOM will look like (for the first example), because it’s invalid HTML, and HTML4 doesn’t define error handling rules.

However, in this case, you can be reasonably sure that browsers will build a DOM where the H1 is a child of the A element, so this selector would match the heading:

a > h1 { ... }

As has been mentioned previously, you cannot have a block level element inside an inline one (in this case a header inside a link). However, you can have an inline level element inside a block level element (a link inside a header).

So this will be valid:

<h1><a href="#">Some Link Text</a></h1>

while this will not be:

<a href="#"><h1>Some Header Text</h1></a>