Wer kennt es nicht, mal wieder bricht die Überschrift um, aber eigentlich dürfte sie lieber kleiner sein als umbrechen, also einfach die Schriftgröße eins - zwei Pixel kleiner, aber nur an den Stellen wo es erforderlich ist!
Das folgende Beispiel zeigt eine Möglichkeit die das ganze automatisiert, wie üblich ohne großes Framework!
Lorem ipsum dolor sit amet, consetetur sadipscing elitr
Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua.
HTML:
<!DOCTYPE html >
<html>
<head>
<meta charset="utf-8" />
<title>fittext</title>
<meta name="author" content="Udo Schmal" />
<style>
.fittoline span { white-space: nowrap; }
</style>
</head>
<body>
<h1 class="fittoline">Lorem ipsum dolor sit amet, consetetur sadipscing elitr</h1>
<p class="fittoline">Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua.</p>
<script src="fittoline.js"></script>
</body>
</html>
JavaScript:
// coding: utf-8
/*! Created by: Udo Schmal | https://www.gocher.me/ */
/* fit text to line by reduce font size */
(function() {
'use strict';
function fitToLine (el) {
if (fitToLine.prototype._singletonInstance) {
var self = fitToLine.prototype._singletonInstance;
} else {
var self = this;
fitToLine.prototype._singletonInstance = this;
this.arr = [];
window.addEventListener('resize', function() {
var i, len=self.arr.length;
for(i=0; i<len; i++) {
self.update(self.arr[i]);
}
});
}
self.init(el);
self.arr.push(el);
}
fitToLine.prototype = {
init: function (el) {
// wrap a span around the content
var span = document.createElement("span");
while (el.hasChildNodes()) {
span.appendChild(el.removeChild(el.firstChild));
}
el.appendChild(span);
this.update(el);
},
update: function (el) {
// get the max width and the max font-size
var elWidth = (el.style.width ? parseFloat(el.style.width, 10) : el.offsetWidth);
var fontSize = (el.style.fontSize ? parseFloat(el.style.fontSize, 10) : 50);
var span = el.firstChild;
while (span.offsetWidth < elWidth) {
el.style.fontSize = ++fontSize + "px";
}
// reduce font-size until span width less then max width
while (span.offsetWidth > elWidth) {
el.style.fontSize = --fontSize + "px";
}
}
};
var i, tags = document.querySelectorAll('.fittoline');
for(i=0; i<tags.length; i++) {
new fitToLine(tags[i]);
}
})();