Breaks the flexbox layout when I wrapped the divs with <a>

Viewed 184

Im trying to make a div within a flex container a clickable link.

.container {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 30px;
}

.flex_container {
  display: flex;
  justify-content: space-around;
}

.box {
  background: silver;
  width: 25%;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid black;
}
<header>
  <div class="container flex_container">
    <div class="box">link1</div>
    <div class="box">link2</div>
    <div class="box">link3</div>
    <div class="box">link4</div>
    <a href="example.com"><div class="box">link5</div></a>
  </div>
</header>

Im trying to make the 4 divs in the container div clickable links. Putting a hyperlink around them as such: <a href="example.com"><div class="box">link</div></a>destroys the layout of the container.

Basically, Im trying to make a top menu bar, with 4 boxes, covering the whole width of the screen.

Thank you.

3 Answers

You can set display: contents for .flex_container>a

contents

The element itself does not generate any boxes, but its children and pseudo-elements still generate boxes and text runs as normal. For the purposes of box generation and layout, the element must be treated as if it had been replaced in the element tree by its contents (including both its source-document children and its pseudo-elements, such as ::before and ::after pseudo-elements, which are generated before/after the element’s children as normal). Ref

.container {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 30px;
}

.flex_container {
  display: flex;
  justify-content: space-around;
}

.box {
  background: silver;
  width: 25%;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid black;
}

.flex_container>a {
  display: contents;
}
<header>
  <div class="container flex_container">
    <div class="box">link1</div>
    <div class="box">link2</div>
    <div class="box">link3</div>
    <div class="box">link4</div>
    <a href="example.com">
      <div class="box">link5</div>
    </a>
  </div>
</header>

just change the div to a <a> like this

.container{
  position: absolute;
  left:0;
  top: 0;
  width:100%;
  height: 30px;
}

.flex_container{
  display: flex;
  justify-content: space-around;
}

.box{
  background: silver;
  width: 25%;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid black;
}
<header>
  <div class="container flex_container">
    <a href="#" class="box">link1</a>
    <a href="#" class="box">link2</a>
    <a href="#" class="box">link3</a>
    <a href="#" class="box">link4</a>
  </div>
</header>

You can use css direct child
Replace .box {/*css*/} by .flex_container>.box, .flex_container>a {/*css*/} or .flex_container>* {/*css*/}

Related