Search code examples
htmlcssflexboxpseudo-elementpseudo-class

Display content in between two div elements via CSS


I'd like to display some "dots" in between a label and a price, like this:

from..........£2,000.49
total........£20,000.00

However, the dots must "adapt/reduce/increase", if the length of the price increases. (Like in the example above), as the prices are dynamic and not static/hardcoded.

I thought I would try this with flex. I have a working example below, where I have two columns, in two rows.

There is no width on the .price-big class, so the width of these divs increases/decreases, with the length of the numbers.

I am then adding the dots to the label class. However, this then pushes my divs onto separate lines/stacked, like in the example below.

.label {
    content: ".............................................";
}

Any ideas on how to achieve this, would be helpful as I'm kinda getting stuck on this one.

Thank you, Reema

.main {
    display: flex;
    flex-wrap: wrap;
    align-items: baseline;
    border: 1px solid green;
    width: 200px;
}

.label {
    font-size: 14px;
    /* flex: 0 50%; */
    flex-basis: 50%;
    flex-shrink: 1;
    flex-grow: 1;
    border: 1px red solid;
    /* width: 100%; */
    text-align: left;
    font-size: 14px;
}

.label:after {
    content: ".............................................";
}


.price-big {
    flex-basis: 0;
    flex-shrink: 1;
    flex-grow: 1;
    border: 1px red solid;
    text-align: right;
    font-size: 20px;
}
<div class="main">
  <div class="label">price</div>
  <div class="price-big total">£2,000.49</div>
  <div class="label">total</div>
  <div class="price-big">£20,000.00</div>
</div>


Solution

  • You may combine float and flex to modify the formating context layout of the non floatting element and use a pseudo to fill that empty space inside it:

    your CSS code modified :

    .main {
        /*display: flex;
        flex-wrap: wrap;
        align-items: baseline;*/
        border: 1px solid green;
        width: 200px;
        overflow:hidden; /* because of the float label */
    }
    
    .label {
        font-size: 14px;
        /* flex: 0 50%;
        flex-basis: 50%;
        flex-shrink: 1;
        flex-grow: 1; */
        border: 1px red solid;
        /* width: 100%; 
        text-align: left;*/
        font-size: 14px;
        margin-top:0.4em;
        float:left;
        clear:left;
    }
     
    
    
    .price-big { 
        border: 1px red solid; 
        font-size: 20px;
        display:flex;
    }
    .price-big:before {
    content:'';
    border-bottom:dotted;
    margin-bottom:0.2em;
    flex-grow:1;
    }
    <div class="main">
      <div class="label">price</div>
      <div class="price-big total">£2,000.49</div>
      <div class="label">total</div>
      <div class="price-big">£20,000.00</div>
    </div>