使用<a>标签包裹<div>会破坏flexbox布局

3
我正在尝试使 flex 容器内的一个 div 可以成为一个可点击的链接。

.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>

我正在尝试将容器div中的4个div制作为可点击链接。在它们周围放置超链接,如下所示:<a href="example.com"><div class="box">link</div></a>会破坏容器的布局。

基本上,我正在制作一个顶部菜单栏,有4个框盖满屏幕的宽度。

谢谢。


Https://codepen.io/arxopxib/pen/MWKPJxg,希望它能帮到你 ^_^ - Ahmed Alduri
3个回答

4
您可以对 .flex_container>a 设置 display: contents

contents

元素本身不会生成任何盒子,但其子元素和伪元素仍会像正常情况下一样生成盒子和文本运行。为了生成盒子并布局,该元素必须被视为在元素树中由其内容替换而来(包括源文档子元素和伪元素,如 ::before 和 ::after 伪元素,在元素的子元素之前/之后生成)。 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>


Https://codepen.io/arxopxib/pen/MWKPJxg,希望它能帮到你 ^_^ - Ahmed Alduri
1
@AhmedAlduri 我不是提出问题的人。 - doğukan
抱歉,我是新来的。 - Ahmed Alduri
嗨,感谢你的回答,但我真的很难理解...真的。你写的内容远远超出了我的理解范围。但还是谢谢。 - Chris
1
我暂时通过将<div>更改为<a>来修复它。 - Chris

3

div 改为这样的<a>

.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>


没问题,很高兴能帮忙! :) 如果我的回答解决了你的问题,你能接受一下吗? :) - Nico Shultz

0
你可以使用 css 直接子元素
.box {/*css*/} 替换为 .flex_container>.box, .flex_container>a {/*css*/}.flex_container>* {/*css*/}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接