Reputation: 518
If an h1 is too long to fit in one line and wraps to the next line, I want those two lines to be roughly the same width. I have searched all over for a CSS solution to this, with no luck.
Is it really true that this is not possible with CSS? It seems like such a simple thing that would be useful in so many instances, so I'm really puzzled that this appearantly can't be done with CSS.
Can anyone recommend some kind of workaround, or what the next best thing might be?
Just to be clear, this is what I mean:
What I want is this:
Upvotes: 9
Views: 2923
Reputation: 51
There is a CSS property called text-wrap: balance
that do exactly what you want.
This is quite new so I'll consider checking the browser compatibility before using it.
See documentation here : https://developer.mozilla.org/en-US/docs/Web/CSS/text-wrap#result
Upvotes: 5
Reputation: 163
I found a solution that works here! It's not CSS, but it is "the next best thing" IMO. It involves jQuery.
Thanks to Kaivosukeltaja!
https://codepen.io/Kaivosukeltaja/pen/jWYqZN
function adjust() {
$('.quote').each(function() {
// Create an invisible clone of the element
var clone = $(this).clone().css({
visibility: 'hidden',
width: 'auto'
}).appendTo($(this).parent());
// Get the bigger width of the two elements to be our starting point
var goodWidth = Math.max($(this).width(), $(clone).width());
var testedWidth = goodWidth;
var initialHeight = $(clone).height();
// Make the clone narrower until it wraps again, causing height to increase
while($(clone).height() == initialHeight && testedWidth > 0) {
goodWidth = testedWidth;
testedWidth--;
$(clone).width(testedWidth);
}
// Set original element's width to last one before wrap
$(this).width(goodWidth);
// Remove the clone element
$(clone).remove();
});
}
$(window).resize(adjust);
$(document).ready(function() {
adjust();
});
body {
background-color: #f0f0f0;
}
.holder {
text-align: center;
margin: 2em auto;
}
.quote {
display: inline-block;
border: 1px solid #c0c0c0;
background-color: #fff;
padding: 1em;
font-size: 40px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="holder">
<div class="quote">
If I want text to wrap, I want the lines as close to equal length as possible.
</div>
</div>
Upvotes: 1
Reputation:
You can try playing with a max-width
and word-break
. Note that if you use word-break: all
maybe create some hyphenation error.
Two examples:
.example-1 {
max-width: 610px;
width: 800px;
word-break: break-word;
}
.example-2 {
max-width: 610px;
width: 800px;
word-break: break-all;
}
<div class="example-1">
<h1>Here is a headline that's too long to fit on a single line, so it wraps to the next line of text</h1>
</div>
<div class="example-2">
<h1>Here is a headline that's too long to fit on a single line, so it wraps to the next line of text</h1>
</div>
Upvotes: 1