2017-02-28 31 views
0

StackOverflow 我曾经使用过HTML,但现在我正在使用完整的SVG项目。我需要创建一个简单的布局:2个矩形,放在一个有间隙的列中,并在每个矩形中放置一个文本。我能做到的唯一方法是用xy手动定位矩形和文本。SVG代码中的DIV

问题:如何才能在HTML中使用它(使用div和相对定位),其中文本是矩形的子项并在其中心对齐?

这就是我做它:

<g> 
    <rect height="40" width="100"/> 
    <text alignment-baseline="baseline" x="30" y="33" font-family="Verdana" style="fill: #fff;" font-size="35">50</text> 
</g> 

谢谢提前。

+1

你有什么已经尝试过? – BenM

+1

@benM我已将我的版本添加到问题中。 – cheremushkin

回答

4

SVG不是像HTML那样的流布局。如果您想在SVG中使用印刷版式功能,您可以使用SVG foreignElement将HTML嵌入到SVG中,例如。

<svg viewBox="..."> 
    <g> 
    <foreignObject x="10" y="20" height="20" width="80"> 
     <div xmlns="http://www.w3.org/1999/xhtml"><p>this</p></div> 
     <div xmlns="http://www.w3.org/1999/xhtml"><p>that</p></div> 
    </foreignObject> 
    </g> 
</svg> 

,然后使用CSS浮筒,Flexbox的,宽度百分比或在div小号任何样式以实现期望的效果。

编辑:foreignObject不会对IE11工作,虽然

+0

谢谢! 但是,如果创建布局的唯一方法是手动定位所有元素,它怎么会如此灵活? – cheremushkin

+0

SVG适用于地图,图表,矢量背景,图标/ avators,游戏内容等,而不是用于布局或旨在替换HTML(以及为什么当您拥有CSS和HTML时) – imhotap

0

如果你可以使用过滤器,您可以在SVG画“格状”文本框。

但是,与原始HTML的div元素相比,这是有点技术性和无用的,因为这个“div-like”没有任何有用的功能,如文本包装,灵活的边框样式,框阴影等。因此,您应该使用原始div元素和foreignObject元素。

示例代码:

/*color setting*/ 
 
.bgcolor{flood-color:yellow;} 
 
.bordercolor{flood-color:orange;} 
 

 
/*filter setting*/ 
 
.divLike{filter:url(#divLike);} 
 
.divLike>text{filter:url(#text);}
<!--define filters--> 
 
<svg width="0" height="0"> 
 
    <defs> 
 
     <!--create bounding box of text--> 
 
     <filter id="text" primitiveUnits="objectBoundingBox"> 
 
      <feFlood x="0" y="0" height="1" width="1" class="bgcolor"/> 
 
      <feMerge> 
 
       <feMergeNode/> 
 
       <feMergeNode in="SourceGraphic"/> 
 
      </feMerge> 
 
     </filter> 
 
     <!--wrap bounding box by feMorphology--> 
 
     <filter id="divLike" x="-1" y="-1" width="3" height="3"> 
 
      <!--create padding--> 
 
      <feFlood class="bgcolor"/> 
 
      <feComposite in2="SourceAlpha" operator="in"/> 
 
      <feMorphology operator="dilate" radius="10" result="padding"/> 
 
      <!--create border--> 
 
      <feFlood class="bordercolor"/> 
 
      <feComposite in2="padding" operator="in"/> 
 
      <feMorphology operator="dilate" radius="5" result="border"/> 
 
      <!--marge these graphics--> 
 
      <feMerge> 
 
       <feMergeNode in="border"/> 
 
       <feMergeNode in="padding"/> 
 
       <feMergeNode in="SourceGraphic"/> 
 
      </feMerge> 
 
     </filter> 
 
    </defs> 
 
</svg> 
 

 
<!--text layout--> 
 
<svg width="500px" height="200px">  
 
    <g class="divLike"> 
 
     <text x="50" y="50" font-size="30">This is <tspan font-weight="bold">div-like</tspan> effect.</text> 
 
    </g> 
 
</svg>