0

Please help. I need to position an svg inside a div, next to a headline. It's a rectangle, kind of a corporate design element. Code:

<div id="container">
   <h1>HEADLINE</h1>
   <img src="/my/rectangle.svg">
</div>

It should look like:

HEADLINE ▮

But in the case of

WRAPPED
HEADLINE

the rectangle should scale up, stretching over two lines, keeping its aspect ratio. So my problem is:
I can't set the height of #container, because I don't know how many lines of text will be in it. When I do as suggested here, meaning say

#container {position:relative}
#container img {position:absolute; height:100%}

the svg will stretch to the right size, but it will overlap with the headline. Any ideas? Thanks!

Edit: Maybe this has nothing to do with svg. Could be any child element that needs to be scaled to parent width. The challenge is that one aspect of the problem requires it to be relative, and the other one requires it to be absolute.

Jan Mirus
  • 263
  • 2
  • 9
  • 1
    ... yes, I could do js; sniffing the height of the headline, setting a height for #container. Probably faster than posting the question here ;) but fixing things like this with js doesn't usually make you feel good. – Jan Mirus Feb 11 '20 at 14:51
  • Also consider using an **actual** SVG element and not an image. – Paulie_D Feb 11 '20 at 15:15
  • Hi Pauli_D, how would using inline svg help me with the challenge that a child element must be absolute in order not to interfere with its parent's height, but must be relative in order to get along with his siblings? – Jan Mirus Feb 11 '20 at 15:50

1 Answers1

1

The simplest option is probably to use display: flex and use background-image for the SVG.

.heading {
  display: flex;
}

.heading h1 {
  margin: 0;
}

.heading .img {
  flex: 1 1 auto;
  background: url(https://dev.w3.org/SVG/tools/svgweb/samples/svg-files/obama.svg) no-repeat;
}
<div class="heading">
  <h1>HEADLINE</h1>
  <div class="img"></div>
</div>

<br/>
<br/>
<br/>

<div class="heading">
  <h1>WRAPPED<br/>HEADLINE</h1>
  <div class="img"></div>
</div>
Paul LeBeau
  • 97,474
  • 9
  • 154
  • 181
  • Hi Paul, many thanks. Using BG no-repeat is a good idea. Honestly I didn't figure out how your example works without setting a width for .heading .img. – Jan Mirus Feb 14 '20 at 19:32
  • I need to set a width, otherwise
    will be 0x0 px. So I chose a width that's as wide as the rectangle will possibly get with double headline, and with single headline the background rectangle only fills the left part. That looks OK, as long as no content is placed right of
    , because the "unfilled" part of
    is still there and pushes other content right. Well. I hope my client won't notice. Thanks!
    – Jan Mirus Feb 14 '20 at 19:46
  • Are you not using `display:flex`? – Paul LeBeau Feb 16 '20 at 09:16
  • On
    ? Yes I am
    – Jan Mirus Feb 20 '20 at 10:00