← Home

Custom tags to get over divitius

@date=2023-08-03
@tags=html

(note: update at end as there some issues with method)

Very often html looks like a soup of divs in projects

<div class="item">
    <div class="name">Toothpaste</div>
    <div class="description">Used to clean teeth</div>
    <div class="price">$20</div>
    <div class="actions"><button>add to cart</div>
</div>

Instead this could look like

<item>
    <name>Toothpaste</name>
    <description>Used to clean teeth</description>
    <price>$20</price>
    <actions><button>add to cart</actions>
</item>

That looks so much better. These are custom element names, and can be used in html. Note that while custom element names <should-have-hyphens> according to the spec (so as to avoid conflicts with future html element names), modern browsers will handle them fine without the hyphens.

One thing you will realize once you start using them is that they are by default display-inline, which is a hassle as you typically want them to be display:block by default as you will be using them to replace divs.

You can handle this by starting out your css for your site like this:

body * {
    display: block;
  }

  /* Revert all of the inline elements back to inline */
  a,
  abbr,
  acronym,
  b,
  bdo,
  big,
  br,
  button,
  cite,
  code,
  dfn,
  em,
  i,
  img,
  input,
  kbd,
  label,
  map,
  object,
  output,
  q,
  samp,
  select,
  small,
  span,
  strong,
  sub,
  sup,
  textarea,
  time,
  tt,
  var {
    display: inline;
  }

UPDATE

After looking further into this, it turns out to be a horrible idea. Many native dom elements have a lot more variety in display settings and to do it the way I am here would need lots of catching for edge cases. For more details:

html.spec.whatwg.org/multipage/rendering.html.

In the end, it is best to just selectively give elements you create the display: block styling as needed. Tedious, but less likely to cause issues.

You could also do something where only elements under a classed element get styled by default. This is done in scss so that the code is shorter:

.auto-display-block-decendents * {
    display: block;
  }
.auto-display-block-decendents{
  /* Revert all of the inline elements back to inline */
  a,
  abbr,
  acronym,
  b,
  bdo,
  big,
  br,
  button,
  cite,
  code,
  dfn,
  em,
  i,
  img,
  input,
  kbd,
  label,
  map,
  object,
  output,
  q,
  samp,
  select,
  small,
  span,
  strong,
  sub,
  sup,
  textarea,
  time,
  tt,
  var {
    display: inline;
  }
}

This list isn't exhaustive, and if you use things like tables, you will need to do re-apply proper styling, but you could use derivatives of this to just apply to isolated components and tweak the exceptions for those cases.