johnbirt
johnbirt

Reputation: 43

Effect of making an <a> a flex container

I have seen that making links a flex container can be useful when vertically/horizontally centering text within a link used in navigation elements. I didn't realise that the link text can actually be a (single) flex item. I can see that span elements within a link can be flex items. I would appreciate an explanation of why it is that the text of a link flex container is a flex item. For example is text in say a div flex container a single flex item - whether it be useful or not!?

I enclose a few examples that might help with comments.

    a {
      border: 2px red solid;
      display: flex;
      flex-direction: row;
      height: 100px;
      width: 250px;
      justify-content: center;
      align-items: center;
      margin:10px;
    }

    a span {
      display: flex;
      flex-direction: row;
      justify-content: center;
      align-items: center;

    }

    a span:nth-child(1) {
      font-size: 20px;
      color: red;
    }

    a span:nth-child(2) {
      font-size: 10px;
    }
  <a href="#">Hello World!</a>
  <a href="#">Hello World! Lorem ipsum dolor sit amet consectetur adipisicing elit.</a>
  <a href="#">Hello World! Lorem ipsum</br>dolor sit amet</br>consectetur adipisicing elit.</a>
  <a href="#"><span>Hello World!</span><span>Good Bye!</span></a>
  <a href="#"><span>Hello World! Lorem ipsum dolor</span><span>sit amet consectetur adipisicing elit.</span></a>

Upvotes: 0

Views: 67

Answers (1)

zzzzBov
zzzzBov

Reputation: 179176

Many of the layout models used by CSS use the concept of anonymous boxes:

An anonymous box is a box that is not associated with any element. Anonymous boxes are generated in certain circumstances to fix up the box tree when it requires a particular nested structure that is not provided by the boxes generated from the element tree. For example, a table cell box requires a particular type of parent box (the table row box), and will generate an anonymous table row box around itself if its parent is not a table row box. (See [CSS2] § 17.2.1.) Unlike element-generated boxes, whose styles inherit strictly through the element tree, anonymous boxes (which only exist in the box tree) inherit through their box tree parentage.

In the case of flexbox, anonymous flex items are created for text runs

Each in-flow child of a flex container becomes a flex item, and each contiguous sequence of child text runs is wrapped in an anonymous block container flex item. However, if the entire sequence of child text runs contains only white space (i.e. characters that can be affected by the white-space property) it is instead not rendered (just as if its text nodes were display:none).

Upvotes: 2

Related Questions