Palaniichuk Dmytro
Palaniichuk Dmytro

Reputation: 3173

Text in flex item must wrap, not shift sibling and expand container

I need to fix the position of a flex container that contains two items: a yellow circle and some text.

When I add more text to the p element, the yellow circle shifts to the left. But I need the circle to hold its position. The text element should not expand; it should wrap.

.flex {
  display: flex;
  align-items: center;
  position: absolute;
  right: 14%;
  top: 15%;
}
.flex .item {
  position: relative;
  width: 5rem;
  height: 5rem;
  background: yellow;
  border-radius: 50%;
}
.flex .item span {
  position: absolute;
  top: 50%;
  left: 50%;
  font-size: 25px;
  transform: translate(-50%, -50%);
}
.flex p {
  margin-left: 10px;
}
<div class="flex">
  <div class="item">
    <span>9</span>
  </div>
  <p>Text here</p>
</div>

Here's a codepen.

Upvotes: 4

Views: 3091

Answers (1)

Michael Benjamin
Michael Benjamin

Reputation: 371231

There are two things missing in your code that can make the layout work:

1. Set a width on the container

Since your container doesn't have a defined width, it will take the width of its content. Like this:

enter image description here

That's the problem you're having.

As shown in the image, the text doesn't wrap because it doesn't need to – there is no width constraint on the container, so it expands to accommodate longer content.

Add this to your code:

.flex { width: 150px; }

Now you have this:

enter image description here

2. Disable flex-shrink

An initial setting of a flex container is flex-shrink: 1. This means that flex items will shrink in order to fit inside the container (preventing overflow).

You can see the result of flex-shrink on the yellow circle in the image above.

You need to disable flex-shrink. Add this to your code:

.flex .item {
  position: relative;
  /* width: 5rem;        <-- remove this; not necessary */
  height: 5rem;
  background: yellow;
  border-radius: 50%;
  flex: 0 0 5rem; /* flex-grow:0 (don't grow), flex-shrink:0 (don't shrink), width:5rem */
}

And now you have this:

enter image description here

.flex {
  display: flex;
  align-items: center;
  position: absolute;
  right: 14%;
  top: 15%;
  width: 150px;
  border: 1px dashed black;
}
.flex .item {
  position: relative;
  /* width: 5rem; */
  height: 5rem;
  background: yellow;
  border-radius: 50%;
  flex: 0 0 5rem; /* NEW */
}
.flex .item span {
  position: absolute;
  top: 50%;
  left: 50%;
  font-size: 25px;
  transform: translate(-50%, -50%);
}
.flex p {
  margin-left: 10px;
}
<div class="flex">
  <div class="item">
    <span>9</span>
  </div>
  <p>text here text here text here text here </p>
</div>

revised codepen

Upvotes: 4

Related Questions