Search code examples
htmlflexboxhyperlink

<a> tag to span multi-row flex items


Is it possible for one <a> tag to span multiple flex items across two or more flex rows?

Example 1:

<div class="inline md:flex md:flex-row md:justify-between">
  <span>word 1</span>
  <span>word 2</span>
  <span>word 3</span>
</div>

<div class="inline md:flex md:flex-row md:justify-between">
  <span>word 4</span>
  <span>word 5</span>
  <span>word 6</span>
</div>

Tailwind Playground link.

.. and somehow have one linkable <a> tag wrap across e.g. word 1-4 or word 2-6 ? This should by default work for both inline and flex layout, depending on breakpoint in media query.


Solution

  • You cannot close a parent tag (In your case the first <div>) without closing all child tags in it (in your case the <a> tag you want to insert), that would be invalid HTML.

    If you try it nevertheless, the browser will try to correct it and close the child tags (i.e. the not-closed <a> tag) before the closing </div> tag, so no, that's not possible.

    ADDITION AFTER COMMENTS:

    A simple grid solution would be something like this:

    .parent {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      grid-template-rows: repeat(3, 1fr);
      grid-column-gap: 20px;
      grid-row-gap: 20px;
    }
    
    .parent span {
      border: 1px solid #ddd;
      padding: 10px;
      min-height: 80px;
      text-align: center;
    }
    
    .parent a {
      display: contents;
    }
    <div class="parent">
      <span>word 1</span>
      <a href="#">
        <span>word 2</span>
        <span>word 3</span>
        <span>word 4</span>
        <span>word 5</span>
        <span>word 6</span>
      </a>
    </div>

    This has an a tag around elements 2-6. Note the display: contents; setting for .parent a, which makes sure the a isn't treated as a grid item, but ignored concerning the grids parent/child relation.

    BTW: You can google "css grid generator" for tools to to generate the grid code according to given settings, which you then can modify, inserting the a tags and your contents.