Home > OS >  CSS Align items in a column depending on content
CSS Align items in a column depending on content

Time:12-03

I have the following html code with own css and bootstrap classes:

<div class="d-flex">
    <p class="table-string">91.86</p>
    <span class="ml-2">( 61%)</span>
</div>
<div class="d-flex">
    <p class="table-string">108.15</p>
    <span class="ml-2">( 108%)</span>
</div>
<div class="d-flex">
    <p class="table-string">329.93</p>
    <span class="ml-2">( 593%)</span>
</div>

And CSS:

.table-string {
    width: 100%;
    text-align: end;
}

I need to recieve column like this:

enter image description here

But actually get this:

enter image description here

How to align values without percentages in a column so that they are strictly under each other: hundreds under hundreds, tens under tens, ones under ones? And also value and percentage must be aligned at the end of the field. Thanks for any help

CodePudding user response:

You need to divide your row into 2 equal halves and align text depending

    <div class="row" style="width:10rem">
    <p class="col-6 p-1 text-end">91.86</p>
    <span class="col-6  p-1 text-start">( 61%)</span>
</div>

and this is an example

Let me know if you need anything else

CodePudding user response:

As a temporary solution, you can use something like this. Just set the width: 50%; of your <p> and <span> tags.

.table-string {
    width: 50%;
    text-align: end;
}
span.ml-2 {
    width: 50%;
    text-align: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA 058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<div class="d-flex">
    <p class="table-string">91.86</p>
    <span class="ml-2">( 61%)</span>
</div>
<div class="d-flex">
    <p class="table-string">108.15</p>
    <span class="ml-2">( 108%)</span>
</div>
<div class="d-flex">
    <p class="table-string">329.93</p>
    <span class="ml-2">( 593%)</span>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Remove d-flex from all the Div's and put d-inline onto all <p>'s and <span>'s instead. With this you most likely do not need the CSS for .table-string so remove that as well.

Eg

<p class="d-inline">91.86</p>
<span class="ml-2 d-inline">( 61%)</span>

CodePudding user response:

Apparently you are using Bootstrap, and if I understood your question, you just need to add two classes to the flex item, flex-column align-items-end, in order to set the direction of flex items and change the alignment on the cross axis:

<div class="d-flex flex-column align-items-end">
[…]
</div>
  • Related