Search code examples
javascripthtmlcsssweetalertsweetalert2

How to position the icon and text horizontally using SweetAlert2 library


I want to change the position of an icon in SweetAlert2 to line up horizontally with a piece of text. (I think I should use display: flex, but as far as I know there is no way to put the icon class inside a div next to the text class).

This is how the alert looks at the moment:

How I have the alert now

And this is how I want it to look:

How I want it to be

Here is the code of my alert:

Swal.fire({
    html: '<span class="text">Congratulations</span>',
    icon: 'success',
    showConfirmButton: false,
    position: 'bottom-end',
    customClass: {
    popup: 'swal-wide',
    icon: 'icon-class'
   }
})  

And here is my CSS file (it currently has nothing important at all):

.icon-class{
    font-size: 10px;
}

.text{
    font-size: 15px;
}

@media screen and (min-width: 761px){
    .swal-wide{
        width: 23% !important;
    }
}
@media screen and (max-width: 760px){
    .swal-wide{
        width: 100% !important;
    }
}

Solution

  • I can't see anything in the SweetAlert2 documentation that would let you do this, but I could be mistaken.

    However, you are correct, it is possible to use divs and flexbox to achieve the effect you want, however, it is a little bit fiddly.

    If you disable the buttons then you will need to implement some other method to remove the sweet alert box.

    The icon is drawn as an svg inside the html property, all within some divs.

    Swal.fire({
      html: '<div class="container"><div><svg class="checkmark" xmlns="http://www.w3.org/2000/svg" viewBox="5 5 40 40"><path class="checkmark__check" fill="none" d="M14.1 27.2l7.1 7.2 16.7-16.8"/></svg></div><div class="textDiv">Congratulations</div></div>',
      position: 'bottom-end',
      showConfirmButton: false,
      customClass: {
        popup: 'swal-wide',
        icon: 'icon-class'
      }
    })
    .icon-class {
      font-size: 10px;
    }
    
    .text {
      font-size: 15px;
    }
    
    @media screen and (min-width: 761px) {
      .swal-wide {
        width: 40% !important;
      }
    }
    
    @media screen and (max-width: 760px) {
      .swal-wide {
        width: 100% !important;
      }
    }
    
    .checkmark {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      border: solid 2px green;
      display: block;
      stroke-width: 2;
      stroke: green;
      stroke-miterlimit: 10;
      stroke-dashoffset: 0;
      margin: 10% auto;
    }
    
    .container {
      display: flex;
      justify-content: center;
      ;
    }
    
    .textDiv {
      padding-left: 10px;
      padding-top: 16px;
      font-family: 'Gill Sans', sans-serif;
    }
    <script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>