Search code examples
htmlcsssweetalert2

How can I use Sweetalert with CSS applied?


I am trying to use the Sweetalert 2 (https://sweetalert2.github.io/) library to pop up a warning message on a page. Even, I think that I am linking the CSS file correctly, the warning message is shown with plain text. The CSS rules are not applied.

I have prepared a minimal page with just the warning message to rule out other reasons, but nothing has changed.

This the head section.

<head>
    <script src="js/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@8"></script>
    <link rel="stylesheet" 
href="https://cdn.jsdelivr.net/npm/sweetalert2@8/dist/sweetalert2.min.css">
</head>

And this is the body.

<body>
    <script>
        $(document).ready(function () {
            Swal.fire({
               type: 'question',
               title: 'Oops...',
               text: 'Something went wrong!',
               footer: '<a href>Why do I have this issue?</a>'
            })
        });
    </script>
</body>

I expect the warning message with CSS applied, but is shown with ugly fonts with no CSS. I checked the console with F12 and there was no error. The browser can reach all required files.


Solution

  • There is nothing wrong with your implementation. SweetAlert2 uses font-family: inherit;, so it will take parent font.

    To solve this, you just need to set the font-family for <body> accordingly.

    Swal.fire({
      type: 'error',
      title: 'Oops...',
      text: 'Something went wrong!',
      footer: '<a href>Why do I have this issue?</a>'
    })
    body {
      font-family: 'Open Sans', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', Helvetica, Arial, sans-serif;
    }
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@8"></script>