2

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):

Visual Explanation of My Problem

Here is a link to my CodePen for a demo as well: https://codepen.io/codezinx/pen/LYOdZXK

Any solutions?

TylerH
  • 20,799
  • 66
  • 75
  • 101
CodeZinx
  • 49
  • 1
  • 7

3 Answers3

0

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>
ash
  • 1,065
  • 1
  • 5
  • 20
  • 1
    The container inside shouldn't be way wider than the text itself. – CodeZinx Feb 20 '22 at 21:52
  • @CodeZinx is that you don't want that inner container. I'm trying hard to understand your concern but I can't, Pleas try to elaborate. – ash Feb 21 '22 at 04:51
-1

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>
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
-2

try to put span HTML element around it

    <pre><span>
    blah blah
    blah blah
    </span></pre>

Hero SHIMA
  • 91
  • 9