我正在尝试使 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/