I found the answer to my question!
The answer is: there is currently no solution using plain HTML. 🙁
Interestingly, Tim Berners-Lee (founder of the world wide web) actually proposed a generic <h>
tag as early as 1991! But it was never adopted formally or used by any major browsers yet.
If you’re using React or Vue, here is a decent solution that will probably work in most cases.
I believe that you are in a situation where you can benefit from using the BEM conventions.
In BEM you have block, elements and modifiers.
For this specific case I would do this.
<div class="custom-component">
<div class="custom-component__header">MY COMPONENT HEADER</div>
<div class="custom-component__content">My component content</div>
</div>
Just define the styles needed for you to make the component look the way you want to.
But what about you need a specific case where the text needs to be slightly different in the header? Let’s say, make it bigger?
<div class="custom-component">
<div class="custom-component__header custom-component__header--big">MY COMPONENT HEADER</div>
<div class="custom-component__content">My component content</div>
</div>
You would just need to write all the css in an appropiate way. I can recommend you to read this documentation:
http://getbem.com/
I have a component that needs header text like this
<div class="custom-component">
<h?>MY COMPONENT HEADER</h?>
<p>My component content</p>
</div>
What element should i use here (in place of <h?>
)?
If I use <h3>
or <h4>
or whatever, i risk breaking the header tree because this component may be used anywhere on the page and could be below an <h1>
, <h2>
, <h3>
or something else. (Note: The HTML spec requires that an <h3>
not follow an <h1>
unless there is an <h2>
in between)
Is there any generic way to define a header element that appropriately defines its content as a header without needing to know beforehand where on the page it will appear in relationship to the other <h#>
elements?
To clarify, I’m not needing any CSS advice. I want a semantic HTML header tag that indicates itself as a header (for my component) that doesn’t require any foreknowledge of other <h#>
‘s within the document — i.e. it should be flexible to be used in a variety of places or pages.
Are the components being rendered dynamically? If so, can you pass the heading level to the component as required?
@FrankFurter The header is not rendered dynamically. But even if it were, that doesn’t address the issue. I am looking for a semantic HTML tag.
glad you’ve found an answer – I was going to suggest the section-specific header element but I believe this was eventually deemed to be bad practice, at least where SEO is concerned (I didn’t get a chance to research it before answering)
Thank you for your efforts. But in my case, I’m wanting semantic HTML tags. I would have no trouble using CSS to make my component look any way I need it to. But this approach is not semantic HTML and, as an aside, also does not provide any SEO benefit.