Matzze Matzze - 3 months ago 17
CSS Question

hide element after line-break

I'm trying to build a responsive footer, but this is maybe interesting for other responsive elements, too.

Is there a possibility to hide an element, if the line breaks at its position?

<footer>
John Doe · Main Street 123 · Sometown · +12 3456 789
</footer>


I want for wide screens:

John Doe · Main Street 123 · Sometown · 012 3456 789


And for smaller screens then for example:

John Doe · Main Street 123 · Sometown
012 3456 789


or

John Doe · Main Street 123
Sometown · 012 3456 789


etc.

So the dividing dot disappears if there is a line break, because it's no more needed and does not look nice at the end or beginning of a line.

Edit: Some possible markup

<footer>
John&nbsp;Doe<span class="hide-when-linebreak"> · </span>Main&nbsp;Street&nbsp;123<span class="hide-when-linebreak"> · </span>Sometown<span class="hide-when-linebreak"> · </span>+12&nbsp;3456&nbsp;789
</footer>


Haven't found any solution for this, maybe there is an idea how to start?

Thx

Answer

You could use this JavaScript function to dynamically set the footer contents on page load and every resize of the window:

$(window).on('resize load', function() {
    var footer = 'John Doe · Main Street 123 · Sometown · +12 3456 789' +
                 ' · jd@example.com · www.example.com';
    footer = footer.trim().replace(/&/g, '&amp;') // encode HTML entities
                          .replace(/</, '&lt;')
                          .replace(/([^·])\s+/g, '$1&nbsp;'); // don't allow breaks here
    var $footer = $('footer');
    var html = ''; // actual content to be put in footer
    var height = 0; // actual height of the footer
    footer.split(/· /).forEach(function (part, i) {
        $footer.html(html + (i ? '· ': '') + part); // try, and see what we get
        // Depending on height increase, place a break or a non-breaking space
        $footer.html(html += (i ? ($footer.height() > height ? '<br>' : '·&nbsp;') : '')
                          + part);
        height = $footer.height();
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<footer></footer>

Comments