【发布时间】:2019-12-04 08:22:12
【问题描述】:
有很多技巧可以解决问题的简单性,这是我的要求:
- 我希望
<hr />元素可见,并切掉一部分(例如;完全透明) -
<hr />的宽度未知 - 剪切区域具有固定尺寸,并且必须位于
<hr />顶部的中心 - 使用 1x
<hr />元素 - 在 IE11 和 Safari 11 以及现代浏览器中受支持
由于浏览器支持,我想我只能在 SVG 中使用 clipPath 并通过 <hr /> 元素上的 CSS 将其设置为剪辑区域。
以下演示尚未在 IE/Safari 中测试,它突出了我尝试首先绘制一个切掉一部分的 SVG 形状。除了我的要求 #2 和 #3 之外,这部分几乎没问题,因为我还没有一个流体填充路径,其中有一个固定且居中的第二个路径。
当我将 SVG 中的 path 转换为 clipPath 然后将其分配给 hr /> 元素时,要求 #1 目前完全失败。
Codepen 演示:https://codepen.io/davewallace/pen/WNNRMoR
标记:
<p>1. Aspect ratio in action, box is correctly centered, but I need the black region to stretch all the way to the far left and right edges, leaving the inner cut-out box in the middle.</p>
<div>
<hr />
<svg xmlns="http://wwww3org/2000/svg" height="32" width="100%" viewBox="0,0,10,10">
<path d="M 0,0 h 10 v 10 h -10 z
M 2,2 v 6 h 6 v -6 z" />
</svg>
</div>
<p>2. So I tried removing the aspect ratio. That sort of helped, but I need the inner cut-out box to be a fixed width and centered.</p>
<div>
<hr />
<svg xmlns="http://wwww3org/2000/svg" height="32" width="100%" viewBox="0,0,10,10" preserveAspectRatio="none">
<path d="M 0,0 h 10 v 10 h -10 z
M 2,2 v 6 h 6 v -6 z" />
</svg>
</div>
<p>3. Regardless of the stretching accuracy of the two techniques above, I expected the supplied paths, converted into a clipPath, to hide the centre part of the HR element, leaving only its left/right sides visible.</p>
<div>
<hr class="clipped" />
<svg xmlns="http://wwww3org/2000/svg" height="32" width="100%" viewBox="0,0,10,10">
<defs>
<clipPath id="square">
<path d="M 0,0 h 10 v 10 h -10 z
M 2,2 v 6 h 6 v -6 z" />
</clipPath>
</defs>
</svg>
</div>
CSS(主要是为了说明):
div {
position: relative;
border: 1px solid red;
margin: 50px;
padding: 20px;
background: #999;
}
hr {
height: 5px;
background: lime;
&.clipped {
clip-path: url(#square);
}
}
svg {
position: absolute;
left: 0;
top: 20%;
border: 1px dotted red;
}
研究至今:
- https://css-tricks.com/clipping-masking-css/
- https://css-tricks.com/cutting-inner-part-element-using-clip-path/
- How can I cut one shape inside another?
到目前为止的替代方法:
- 使用 flexbox 并有 1 个
<hr />、一个间隙,然后是另一个元素,如<div />,完成后半部分的效果。所以它不是在<hr />中“挖一个洞”,而是在视觉上停止和启动它。在我的上下文中,这种方法需要一些神奇的数字并且不是那么干净。很确定它仍然可以访问,因为我仍在使用 1x<hr />元素,主要是因为它打算被使用。 - 到目前为止还没有别的,但这是为了实现“花哨的水平线”效果,人们可以将他们的图像/SVG 资源放到水平线的中间,而不必担心水平线会在资源下方。我也不知道页面背景颜色是什么,不能做任何假设。
谢谢!
【问题讨论】:
-
你总是会在你的元素中隐藏一个正方形的部分?
-
嗯,理想情况下,我希望能够为内框提供自定义宽度/高度值,以便可以在
的中心使用不同的图像/SVG。不过,我现在会满足于中间部分的“永远正方形”:) -
那么在这种情况下,让你的元素只有边框并控制它们的宽度。您将轻松地将广场置于中心