SVG元素的绝对定位无法正常工作

8

我尝试设置一条 SVG 线,让它在所有设备上都可以将屏幕划过。在移动设备和屏幕较小的计算机上,线条会被截断,就像我图片中的下面那个示例。

enter image description here

我试过将 <svg> 元素设置为绝对定位,但只是将它放在一个 <div> 中,甚至没有给该 div 任何 CSS 样式就会改变它。有什么建议吗?

这里有个演示。

1个回答

20

你需要将svg元素包裹在一个div(.svg-container)中,这个div需要在主区域(.sec1)内绝对定位,以使其可以“穿过”它。然后需要对主区域应用相对位置,以便包装器div知道如何相对于其进行定位:

HTML

<div class="sec1">
  <div class="svg-container">
   <svg height='100%' width='100%' xmlns='http://www.w3.org/2000/svg'>
    <line stroke='#5AB1BB' stroke-width='2' x1='0' x2='10000' y1='0' y2='10000'></line></svg>
  </div>
  <div class="w3-container">
    <div class="maintitlesection">
      <div class="title">
        William Stinson
      </div>
      <p>Computers, graphics, photo and video (and lots more).</p>
    </div>
  </div>
</div>

CSS

->

CSS

.sec1 {
  position: relative;
}

.svg-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.maintitlesection {
  position: absolute;
  width: 300px;
  right: 30px;
}

这里是一个代码片段


1
@WilliamStinson 这是因为.w3-container在两个部分中都被使用了。请查看我的更新答案,我们只对.maintitlesection应用样式,使其出现在右侧。 - Susanne Peng
谢谢。你救了我们的一天。 - Anbhu

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