html - 当我用 <a> 包裹 div 时破坏了 flexbox 布局

标签 html css flexbox

我正在尝试使 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 个框,覆盖整个屏幕宽度。

谢谢。

最佳答案

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

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>

关于html - 当我用 <a> 包裹 div 时破坏了 flexbox 布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62932840/

相关文章:

HTML/CSS - 页脚不会推到底部且图像无法正确对齐

javascript - 动态加载新的 css 文件时字体闪烁

html - 尝试使用垂直居中文本创建圆圈并且存在下圆文本

html - 如何使用 flex box 使图像垂直居中?

angular - Openlayers map 不使用全宽

javascript - 格式化文本中的数字

html - 如何在黑色背景上创建以图片为背景的透明 div?

javascript - jQuery Accordion - 将选定的一个向上移动

html - 打破这些界限的语义正确方法是什么?

javascript - 如何使用 html、css 和 js 添加自定义动画弹出按钮?