2

I have a container with 2 children. First child is an icon and second is text. I want to align the icon left and the title center using Flexbox only.

The HTML code and the CSS code:

.container {
  display: flex;
  background-color: #7D8F99;
  width: 100%;
  height: 50px;
}

.title {
  display: flex;
  background-color: #9AADB8;
}

.icon {
  display: flex;
  background-color: #1AADA9;
}
<div class="container">
  <span class="icon">icon</span>
  <span class="title">text</span>
</div>

https://jsfiddle.net/eajosjoh/

kevin b.
  • 1,494
  • 1
  • 13
  • 23
Ioan Ungurean
  • 319
  • 1
  • 15

2 Answers2

3

A combination of position: absolute and left: 0 on the .icon would do the trick.

.container {
  display: flex;
  justify-content: space-around;
  background-color: #7D8F99;
  width: 100%;
  height: 50px;
  position: relative;
}

.title {
  background-color: #9AADB8;
}

.icon {
  background-color: #1AADA9;
  position: absolute;
  left: 0;
}
<div class="container">
  <span class="icon">icon</span>
  <span class="title">text</span>
</div>

Or, if you wanted to use only flex, you could add an empty spacer element on the right side. The spacer element would need to have the same width as the .icon element. And honestly, adding an empty element for the sake of layout isn't a great option. So I'd recommend the first method.

.container {
  display: flex;
  justify-content: space-between;
  background-color: #7D8F99;
  width: 100%;
  height: 50px;
}

.title {
  background-color: #9AADB8;
}

.icon {
  background-color: #1AADA9;
  width: 30px;
}

.spacer {
  /* width must match icon width */
  width: 30px; 
}
<div class="container">
  <span class="icon">icon</span>
  <span class="title">text</span>
  <span class="spacer"></span>
</div>
Brett DeWoody
  • 59,771
  • 29
  • 135
  • 184
1

Adding a margin: 0 auto; to the .title will solve the problem

.container {
  display: flex;
  background-color: #7D8F99;
  width: 100%;
  height: 50px;
}

.title {
  display: flex;
  background-color: #9AADB8;
  margin: 0 auto;
}

.icon {
  display: flex;
  background-color: #1AADA9;
}
<div class="container">
  <span class="icon">icon</span>
  <span class="title">text</span>
</div>
Saravanan I
  • 1,229
  • 6
  • 9