Can't center element with wrapped text because text wrapping sets parent to 100% width

Viewed 238

I've got an issue with wrapping text.

I'd like the content of my item to be centered (Which I've done with justify-content: center;)

But when the text wraps - I would like that text to be aligned to the left.

However, when the text does wrap, the the width of the parent element is automatically 100%. So while the text IS left aligned, the content doesn't seem centered, because it can't really be centered with a 100% width.

I hope that makes sense!!

Any help would be great!

Here's a fiddle of my problem: https://jsfiddle.net/whqbonad/38/

.container {
  width: 300px;
  margin: 0 auto;
 }

.item {
  width: 50%;
  float: left;
  background: #e3e3e3;
  margin: 10px 0;
  padding: 20px;
  box-sizing: border-box;
 
  display: flex;
  justify-content: center;
}
<div class='container'>
  <div class='item'>
    <span>Hello 1</span>
  </div>
  <div class='item'>
    <span>Hello 2</span>
  </div>
  <div class='item'>
   <span>Hello 3</span>
  </div>
  <div class='item'>
    <span>Hello 4</span>
  </div>
  <div class='item'>
    <span>Hello 5</span>
  </div>
  <div class='item'>
    <span>Hello but longer!</span>
    <!-- I want this to be centered, but the text be left aligned -->
  </div>
</div>

1 Answers

this code work properly

.container {
  width: 300px;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  margin: 0 auto;
}

.item {
  flex-basis: 50%;
  background: #e3e3e3;
  margin: 10px 0;
  padding: 20px;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  text-align: center;
  justify-content: center;
}

span {
  display: block;
  width: 80%;
  background: red;
  text-align: left;
  height: 100%;
}
<div class='container'>
  <div class='item'>
    <span>Hello 1</span>
  </div>
  <div class='item'>
    <span>Hello 2</span>
  </div>
  <div class='item'>
    <span>Hello 3</span>
  </div>
  <div class='item'>
    <span>Hello 4</span>
  </div>
  <div class='item'>
    <span>Hello 5</span>
  </div>
  <div class='item'>
    <span>Hello but longer!</span>
  </div>
</div>

Related