首页 > 解决方案 > 在项目之间绘制边框,无论它们是并排放置还是换行

问题描述

我有两个内联块 A 和 B,它们的尺寸都是可变的:

<container style="display: flex; flex-wrap: wrap">
    <div>Arbitrary content A</div>
    <div>Arbitrary content B</div>
</container>

根据它们的内容和屏幕大小,它们可能并排放置,或者 B 可能需要换行。正如所展示的,这很容易通过 flexbox 实现。

但无论最终以哪种方式布局,我想在两个块之间画一条线,如下所示:

AAA │ BBB
AAA │ BBB
AAA
AAA
───
BBB
BBB

通常你会用媒体查询来解决这种布局问题,但由于布局是基于内容的,媒体查询不会削减它。

排除媒体查询后,我想不出任何好的方法来实现这一点——像 a 这样的任何东西都border适用于指定的边缘,并且不能依赖于布局。

我不介意使用什么布局技术,即使需要添加更多 DOM 节点才能使其工作,只要不需要 JavaScript。我很确定 Grid 不能工作,因为这需要类似grid-template-columns: repeat(auto-fit, auto)which 不起作用的东西(auto-fit需要固定尺寸)。

我只关心两个项目的情况;三个或更多变得更加混乱,我相当有信心用手头的工具无法解决,而两个感觉可能是可以解决的。

有人对绘制此边框有任何想法吗?

标签: cssflexbox

解决方案


如果此处不需要透明度,则此解决方案涉及一些背景,您可以在其中轻松控制线条的大小:

.container {
  display: flex;
  flex-wrap: wrap;
  border:1px solid;
  margin:10px;
  background:
    linear-gradient(red,red) center
    /
    calc(100% - 2*2px - 100px) /* length of horizontal line (we at least remove the thickness of the vertical line)*/
    calc(100% - 2*1px - 10px) /* length of vertical line (we at least remove the thickness of the horizontal line)*/
    no-repeat;
}
.container > * {
  padding:20px;
  background:#fff;
  flex-grow:1;
  margin:1px 2px; 
   /* 1px*2 = thickness of the horizontal line */ 
   /* 2px*2 = thickness of the vertical line */
}
<div class="container" >
  <div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus vel venenatis sapien, </div>
  <div>Arbitrary content B</div>
</div>

<div class="container" >
  <div>Lorem ipsum dolor sit amet </div>
  <div>Arbitrary content B</div>
</div>


推荐阅读