Sweet alert 2 - position swal in middle of a div

Shay picture Shay · Oct 15, 2017 · Viewed 9.3k times · Source

I need to position a Swal in the middle of a div. According the documentation: https://sweetalert2.github.io/

it can be done with "target" param but It's not working for me.

I have prepared the following JSFiddle to demonstrate the issue:

swal({
      title: 'Hello',
      target: ".myClass"
        });

JSFiddle

Thanks.

Answer

taekwondoalex picture taekwondoalex · Mar 1, 2018

The target param needs to be used with document.getElementById('myDiv') rather than ".myClass"

swal({
    title: 'Hello',
    target: document.getElementById('myDiv')
});

All the target param does is let you determine which div or element the sweetalert2 div gets appended to. The default is <body> but if you specify a div, you will still get a full screen overlay, the code is simply appended into the div of your choice.

As a work around you could provide some override CSS in your style sheet:

#myDiv .swal2-container {
    position:inherit;
    height:500px;
    width:500px;
}

<div class="myClass" id="myDiv"></div>

But this will only work if your div is empty, as soon as you put anything in the div, the alert will be offset underneath any content.