'How do I prevent a center-aligned heading from extending full-width on line break in a flex container? (HTML/CSS) [duplicate]
As the title says, how do I prevent the heading from extending full-width during a line break?
The heading is inside a container with display: flex;
and align-items: center;
Here is a visual explanation to explain my problem better (blue line represents flex container):
Here is a link to my CodePen for a demo as well: https://codepen.io/codezinx/pen/LYOdZXK
Any solutions?
Solution 1:[1]
Displaying the grid helps us to easily place items on the DOM. That's why I used display: grid then as we have to center the item. I used place-items: center. And that line white space : wrap help to move text to next line.
body{
display: grid;
place-items: center;
}
.b {
display: -webkit-box;
width:10rem;
border : solid black;
white-space: wrap;
height: auto;
overflow: hidden;
text-overflow: ellipsis;
font-size:2.5rem;
text-align: center;
}
div {
background-color: lightgrey;
width: 300px;
border: 15px solid black;
padding: 50px;
margin: 20px;
}
<div class="a">
<div class="b">
lorem ipsum
</div>
</div>
Solution 2:[2]
The simplest way would be to change your h1 padding from: padding: 10px;
to padding: 10px 50px
.
body {
margin: 0;
padding: 0;
}
.container {
display: flex;
flex-direction: column;
align-items: center;
padding:30px;
width: 50%;
}
h1 {
background-color: #444;
color: white;
text-align: center;
font-size: 3rem;
padding: 10px 50px;
}
<!DOCTYPE html>
<html>
<body>
<div class="container">
<h1>Just some random text lorem ipsum si dolor amet</h1>
</div>
</body>
</html>
Solution 3:[3]
try to put span HTML element around it
<pre><span>
blah blah
blah blah
</span></pre>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | |
Solution 3 |