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!
HTML:
<!DOCTYPE html >
<html>
<head>
<title>fittext</title>
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: " />
<script type="text/javascript" src="jsFitText.js"></script>
</head>
<body>
<h1 class="fittoline" style="border:1px solid black;">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut</h1>
</body>
</html>
JavaScript:
function fitText(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);
if (!el.getAttribute("data-type") || (el.getAttribute("data-type") != "fittoline")) {
// wrap a span around the content
var span = document.createElement("span");
while (el.hasChildNodes()) {
span.appendChild(el.removeChild(el.firstChild));
};
el.appendChild(span);
span.style.display = "inline-block";
try {
span.style.font = "inherited";
} catch(err) {
// IE lt 9 fallback
span.style.fontSize = "20px";
}
span.style.whiteSpace = "nowrap";
// set values for the next access (resize)
el.setAttribute("data-type", "fittoline");
el.setAttribute("data-font-size", fontSize);
} else {
var span = el.firstChild;
while ((span.offsetWidth < elWidth) && (el.getAttribute("data-font-size") > fontSize)) {
el.style.fontSize = ++fontSize + "px";
};
}
// decrease font-size until span width less then max width
while (span.offsetWidth > elWidth) {
el.style.fontSize = --fontSize + "px";
};
};
function initFitText() {
var i, tags = document.getElementsByTagName('h1');
for(i=0; i<tags.length; i++) {
var sClass = " "+tags[i].className+" ";
if (sClass.indexOf(" fittoline ") !== -1) {
fitText(tags[i]);
}
}
}
if (window.addEventListener !== undefined) { // W3C
window.addEventListener('load', function() {initFitText();});
window.addEventListener('resize', function() {initFitText();});
} else if (window.attachEvent) { // old IE
window.attachEvent('onload', function() {initFitText();});
window.attachEvent('onresize', function() {initFitText();});
} else { // fallback
window.onload = function() {initFitText();};
window.onresize = function() {initFitText();};
}