Is it possible to horizontally center align some text if it fits in a single line, but do not do center align and do white-space: normal
if it takes up multiple lines (preferrably, but not necessarily, without javascript)?
Here is an HTML+CSS solution.
The tricks are:
The <span>
inside <p>
has the display: inline-box;
property so it will shrink to the size of its content.
The <p>
has text-align: center
so the <span>
will be centred if the size of the <span>
is less than the width of the <p>
.
The <span>
has text-align: left
so the text will actually be left-aligned.
<!DOCTYPE html> <html>
<head>
<title>Center</title>
<style type="text/css">
.big-box {
text-align: center;
width: 40em;
border: 1px solid red;
}
.center-if-single-line {
text-align: left;
display: inline-block;
border: 1px solid blue;
}
</style>
</head>
<body>
<div>
<h1>Small</h1>
<p class="big-box">
<span class="center-if-single-line">
All your line are belong to us!
</span>
</p>
<h1>Big</h1>
<p class="big-box">
<span class="center-if-single-line">
All your line are belong to us!
All your line are belong to us!
All your line are belong to us!
All your line are belong to us!
All your line are belong to us!
All your line are belong to us!
All your line are belong to us!
All your line are belong to us!
All your line are belong to us!
All your line are belong to us!
All your line are belong to us!
All your line are belong to us!
All your line are belong to us!
All your line are belong to us!
All your line are belong to us!
</span>
</p>
</div>
</body>
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With