Home > OS >  CSS how to keep space between two elements if both are displayed and keep right element to the right
CSS how to keep space between two elements if both are displayed and keep right element to the right

Time:07-10

I'm currently displaying two icons and I kept space between them using flex-box property justify-content and value space-between. The problem is that sometimes only one icon is going to be displayed and I need the V-icon to always stay to the left and the urgent-icon to the right. I tried to use floats(right/left) or some flex-box properties like justify-self: end or flex-end but it did not work. The urgent-icon goes to the left and it should always stay to the right. Is is possible to achieve it with flex-box? Where did I make mistake?

<div >
    <a  (click)="navigateToDetails($event)">{{request.id}}</a>
    <div >
        <img src="assets/v-icon.svg"
             title="Urgent Request" (click)="navigateToDetails($event)"
             [tooltip]="'Link redirects to Vendor Req.: '   request.id"
             [options]="{'tooltip-class': 'tooltip-style', 'placement': 'top'}">
        <img *ngIf="request?.urgent" height="22" width="22" src="assets/urgent-icon.svg"
             >
    </div>

</div>

Current result

Expected result

CodePudding user response:

Just give the right icon margin-left:auto

div {
  width: 150px;
  border: 1px solid red;
  padding: 1em .25em;
  display: flex;
  justify-content: space-between;
  margin: 1em;
}

span:last-of-type {
  margin-left: auto;
}
<div><span>1</span><span>2</span></div>

<div><span>2</span></div>

CodePudding user response:

You can create a spacer between images, with flex: 1 1;

.main{
    width: 50%;
    height: 50px;
    background: rgb(200, 200, 200);
    display: flex;
}

.spacer{ /* this will expand into all the space left over */
    flex: 1 1;
}

span{
    height: 100%;
    width: 50px;
    background: rgb(150, 100, 255);
}

.red{
  background: rgb(255, 100, 100);
}
<div >
    <span></span>
    <div ></div> <!-- Add this between the images -->
    <span ></span>
</div>
<br>
 <div >
    <div ></div> 
    <span ></span>
</div>
<br>
<div >
    <span></span>
    <div ></div>
</div>

  • Related