Search code examples
csstextflexboxfixed-width

Text occupying more space than needed using flexbox


I'm trying to draw a square next to a multiline piece of text in a fixed width container for a color legend. However, I'm running into the issue that even though the text and the square should fit in the container, the square is getting squashed into a rectangle as the text element takes up more horizontal space than it should. Is there a way I can (preferably without hard-coded magic numbers) ensure that the p element only takes the horizontal space it needs to display the text?

Relevant MWE:

html:

<div class="div">
  <div class="square">
  </div>
  <p class="text">
    Lorumipsum  dolorsitamet
  </p>
</div>

css:

.div {
    width: 140px;
    display: flex;
    align-items: center;
    outline: 1px solid blue;
}

.square {
    width: 25px;
    height: 25px;
    background-color: red;
}

.text {
    margin-left: 2px;
    outline: 1px solid red;
}

Fiddle: http://jsfiddle.net/6jxtp8k5/59/


Solution

  • Use min-width and min-height instead of using width and height. This will ensure that the square will always have the specific width and height.

    .square {
        min-width: 25px;
        min-height: 25px;
        background-color: red;
    }