Reputation: 11796
Is it possible to center the text in css and make it expand from left and right without using javascript and without knowing how big is it?
In my attempts the text always expands to the right.
.container {
width: 90px;
border: 1px solid red;
text-align: center;
white-space: nowrap;
overflow: visible;
}
<div class="container">Hello very long text</div>
<div class="container">Small text</div>
Upvotes: 0
Views: 139
Reputation: 12108
You can do it with the Flexbox:
.container {
display: flex; /* displays flex-items (children) inline */
justify-content: center; /* centers them horizontally */
width: 90px;
border: 1px solid red;
/*text-align: center;*/
white-space: nowrap;
overflow: visible;
}
<div class="container">Hello very long text</div>
<div class="container">Small text</div>
Upvotes: 2
Reputation: 67778
What you can do is the solution below: Make the container position: relative
, put aspan
in that and apply the settings below to that span to center it (position: absolute etc.)
You'll have to give some height to the container to make that work though.
.container {
width: 90px;
border: 1px solid red;
white-space: nowrap;
overflow: visible;
text-align: center;
position: relative;
height: 1.4em;
}
.container>span {
display: block;
position: absolute;
left: 50%;
transform: translateX(-50%)
}
<div class="container"><span>Hello very very very long text</span></div>
<div class="container">Small text</div>
Upvotes: 3