2

I want to center a div inside another div, so I am using flex to accomplish this. The flex container is set up, and the flex item has some text inside of it. I can get the flex item to adjust its size to it's contents, but I'm running into an issue when I have a piece of text that wraps, like so:

div.flex-container {
  max-width: 400px;
  border: 1px solid blue;
  display: flex;
  justify-content: center;
  align-items: center;
}

div.flex-item {
  padding: 1rem;
  border: 1px solid red;
  flex: none;
  max-width: calc(100% - 2rem);
  width: fit-content;
  width: -moz-fit-content;
}

h2 {
  /* need to wrap and not force parent to be 100% */
}
<div class="flex-container">
  <div class="flex-item">
    <h2>HERE IS TEXT TO SEEEEEEEEEE</h2>
    <p>Lorem ipsum dolor sit amet, consetetuar</p>
    <a href="#">here is a link</a>
  </div>
</div>

You'll notice that the flex item takes up the full space of the parent div, because the wrapped content takes the full width of its parent regardless of the visual width of the h2. If I set the width of the h2 to 0, the flex item does in fact shrink to the next largest element, like so:

div.flex-container {
  max-width: 400px;
  border: 1px solid blue;
  display: flex;
  justify-content: center;
  align-items: center;
}

div.flex-item {
  padding: 1rem;
  border: 1px solid red;
  flex: none;
  max-width: calc(100% - 2rem);
  width: fit-content;
  width: -moz-fit-content;
}

h2 {
  /* need to wrap and not force parent to be 100% */
  width: 0;
}
<div class="flex-container">
  <div class="flex-item">
    <h2>HERE IS TEXT TO SEEEEEEEEEE</h2>
    <p>Lorem ipsum dolor sit amet, consetetuar</p>
    <a href="#">here is a link</a>
  </div>
</div>

Visually what I want is for the text to be able to wrap normally without forcing the flex item to be the full width of the flex container. Is this possible without affecting the layout of the content?

codeWonderland
  • 297
  • 1
  • 11

0 Answers0