I need a solution to display an icon in front of headlines that vary in length, sometimes spanning one line and other times extending to two lines. The challenge is to ensure the icon resizes accordingly to match the height of the headline element.
Currently, the SVG occupies all available space within its container, resulting in icons that are always as large as the .svg-container itself. To address this issue, I aim to make the .svg-container square-shaped, mirroring the dimensions of the svgs it holds. This means the container should have a height equal to that of the .headline element, serving as both the height and width for the .svg-container.
To achieve this goal, I attempted to retrieve the height of the .headline span (or possibly a div) using $('.headline').height();
and then apply this value to the .svg-container via .css()
.
However, I encountered difficulties as the actual height returned was 0. I experimented with obtaining the heights of other elements on the page, but I consistently received values of 0, -2, or 2.
My research revealed that wrapping the code inside $(document).ready(function(){
was necessary, yet it failed to rectify the situation.
$(document).ready(function() {
var headlineHeight = $('.headline').height();
$('.svg-container').css('width', headlineHeight)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1 class="spacing-after headline-with-icon">
<span class="svg-container">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
viewBox="0 0 40 40" style="enable-background:new 0 0 40 40;" xml:space="preserve">
<use xlink:href="#icon-1"/><!-- takes the icon form an svg sprite -->
</svg>
</span>
<span class="headline">Headline in here</span>
</h1>