Bootstrap modal appearing under background
Asked Answered
R

68

714

I have used the code for my modal straight from the Bootstrap example, and have included only the bootstrap.js (and not bootstrap-modal.js). However, my modal is appearing underneath the grey fade (backdrop) and is non editable.

Here's what it looks like:

modal hiding behind backdrop

See this fiddle for one way to reproduce this problem. The basic structure of that code is like this:

<body>
    <p>Lorem ipsum dolor sit amet.</p>    

    <div class="my-module">
        This container contains the modal code.
        <div class="modal fade">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-body">Modal</div>
                </div>
            </div>
        </div>
    </div>
</body>
body {
    padding-top: 50px;
}

.my-module {
    position: fixed;
    top: 0;
    left: 0;
}

Any ideas why this is or what I can do to fix this?

Roderick answered 17/5, 2012 at 13:27 Comment(7)
In case someone else searches for some time for open tags, etc. trying to figure out why this is happening, for me it was the Feedly chrome extension that broke my modals. Disabling the extension returned behavior to normal.Succinylsulfathiazole
In may case the problem was on iOS and caused by overflow-x: hidden applied to the container of the modal.Dewar
Created 3 examples across 3 versions. 3.3.1 works fine and the others don't. Version 3.3.1 jsfiddle Version 3.3.5 jsfiddle Version 3.3.6 jsfoddleAntedate
Created a bug report with Bootstrap team seems like this is not really a bug even thought it worked fine in 3.3.1. You can read more about it in the link I posted.Antedate
A blog post of relevance to anybody facing this issue weblog.west-wind.com/posts/2016/Sep/14/…Anglosaxon
Maybe it helps someone in future. In my case, the issue was separate Js and CSS version.Blandina
If you're fine with removing the backdrop, you can pass a bool via JS options or data-* attribute: getbootstrap.com/docs/3.3/javascript/#modals-usageThrough
M
779

If the modal container has a fixed or relative position or is within an element with fixed or relative position this behavior will occur.

Make sure the modal container and all of its parent elements are positioned the default way to fix the problem.

Here are a couple ways to do this:

  1. Easiest way is to just move the modal div so it is outside any elements with special positioning. One good place might be just before the closing body tag </body>.
  2. Alternatively, you can remove position: CSS properties from the modal and its ancestors until the problem goes away. This might change how the page looks and functions, however.
Midge answered 3/8, 2012 at 3:9 Comment(19)
Good catch. FYI, not just "fixed", the parent's postion "relative" causes this problem as wellMudlark
Using a sidebar with fixed position. Pulling it out of that div did the trick. Thanks.Casillas
@Midge how do you make sure it and all of its parent elements are positioned the default way?Ambition
Prefer use the option one : " just move the modal div so it is outside any elements with special positioning". ThxJulissa
Solution 1 was my issue, and moving the modal container did the trick.Amino
I don't understand this answer. The Bootstrap examples show a modal div with a number of classes along the line of "modal","modal-fade", etc. Inside .modal it sets position:fixed, and inside "modal-body" it sets position:relative. So how is moving the modal container going to change anything, when .modal sets position:fixed?Pleasance
i got this problem still. I add it right before </body> and body doens't have any position style attrib. Any other idea?Etz
Also "navbar-static-top" attribute can cause the problem - spend a whole day to get it works!Epicarp
This solution is no longer relevant it seems.Howdah
Had this same exact issue, but in my case all parent elements had no position settings to speak of. However, I found that -webkit-overflow-scrolling: touch; together with overflow-y: scroll for smooth scrolling on iOS was causing it. Removing it would have done the trick, but I chose option 1 instead.Valerio
Outstanding! For those of you using ASP.NET MVC (and partial views with layout files), be aware that your modal div may need to reside in a different page than your input trigger/button. For me, I had to put my modal div in my parent layout page, right inside the </body> tag.Xylography
@muhd This answer saved my life. Thanks so much, I was tearing my hear apart for many hours. I would have gone bald pretty soon :)Outworn
I see this even with a parent element way up the chain that has position: absolute. If I remove that it works. Unfortunately I can't move the element elsewhere because it's being dynamically rendered by a component.Mcardle
Something else worth checking: it may be that you haven't closed a <div>, meaning that a style is still being applied when it shouldn't be.Satirical
is the dialog is wrapped inside of a <section></section> tag. position: relative would be added and it'll cause it. in my case, I removed the wrapped <section></section> and everything worked as expectedLuzluzader
Great answer! I think it is worthy to note that if it still loads on the body with the backdrop, the problem will persist. I apend it to the html document and it loads on top. jQuery(function($) { $('#myMOdal').appendTo("html") });Rustle
For me it works correctly inside a relatively-positioned element (BS 3.3.7). However the problem occurred on one page that creates stacking context (by adding z-index) on that element. So instead of removing position: I had to remove the z-index: and redesign the parts depending on it (simply by putting them inside an inner DIV).Purposive
My solution was: Giving modal-backdrop -> z-index: 1 and modal-dialog -> z-index: 2Tarsia
my problem fixed by changing the location of modal.Rakes
S
483

The problem has to do with the positioning of the parent containers. You can easily "move" your modal out from these containers before displaying it. Here's how to do it if you were showing your modal using js:

$('#myModal').appendTo("body").modal('show');

Or, if you launch modal using buttons, drop the .modal('show'); and just do:

$('#myModal').appendTo("body") 

This will keep all normal functionality, allowing you to show the modal using a button.

Smyth answered 3/4, 2013 at 7:0 Comment(6)
Use that generic event handler to make @leandrotk solution work for all modals you can have in a page $('.modal-dialog').parent().on('show.bs.modal', function(e){ $(e.relatedTarget.attributes['data-target'].value).appendTo('body'); })Lh
This works great when you really can't fix the CSS positioning. Thanks :)Exoskeleton
From leandrotk answer, just change #myModal to .modal to look like this: $('.modal').appendTo("body"). This will work with all the modals since they have a default class modal.Bombsight
@EugenevanderMerwe - it is no longer inheriting any css from parent-elements within body.Has
Still relevant for bootstrap5, thanks!Incommode
great solution! I used plain js: document.body.appendChild(document.getElementById('myModal'));Sarchet
P
196

I tried all options supplied above but didn't get it to work using those.

What did work: setting the z-index of the .modal-backdrop to -1.

.modal-backdrop {
  z-index: -1;
}
Phyl answered 14/11, 2014 at 1:7 Comment(14)
This worked perfectly and is by far the easiest solution. I used z-index: 0;Rowdyism
Can also confirm that only this options works! Thanks!Aerothermodynamics
Thanks! Is this a bug on BS3?Loon
Worked as of May 2015 on Bootstrap v3.3.4 -- but make sure you add this CSS in the document after you link to the bootstrap.css file!Forename
A better solution is .modal-backdrop.in { z-index: auto;}Roundsman
This doesn't work if you're using a theme that has many varying z-indices. For example, setting the backdrop to -1 would cause it to appear behind other elements on the page such as panels. But setting it to 3 made it above everything except the modal popup.Howdah
I found this to be the fastest method as well after exhausting the suggestions in the answers rated higher above. In my case setting the div with the modal-dialog class to a z-index of 1060 popped it in front of the overlay. If you use the navbar you will want to move the modal above the overlay and not the other way around, otherwise your navbar may pop on top of the overlay... chaos insues...Cuckoopint
The most easiest and fastest solution.Sumac
I agree. Least invasive solution. I used @hellion's modification and it worked as well. I am no expert on the z-index by any stretch but this answer plus the cautions in the comments seem the best solution for me. I am using Angular and it would be more difficult to apply the selected answer which may be the best in other situations.Shriver
I can also confirm that this worked like a charm for me with Bootstrap 4Move
@JustinSkiles true, if other elements show up on top of the backdrop element then you can also change the modal's z-index accordingly with a high value like others suggested.Manassas
I had case where the application 'suddenly' stopped working correctly. Turns out a missing .css file that was re-included in the project was setting z-index values all over the place. This solution worked thereby indicating the problem of gratuitous use of z ordering elsewhere. So... just because you CAN set the z-index doesn't mean you SHOULD set it and if you find yourself setting in all over the place you're probably doing something wrong.Irs
This worked for me as well! I accidentally came across the z-index property and discovered the solution on my own. I wanted to share it, but when I scrolled down I saw this answer.Mariejeanne
Working using !important with thisIrresponsible
N
152

Also, make sure that version of BootStrap css and js are the same ones. Different versions can also make modal appearing under background:

For example:

Bad:

<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>

Good:

<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
Narcotic answered 14/11, 2014 at 10:18 Comment(5)
Just had the same problem, same version stylesheet solution seems to have helped everyone! ThanksAngelicangelica
Malcor no problems, i've spent a lot of time while i figured this bug out. As we see that was in '14, now is '16, bug still exist. Actually this is not a bug, but in bootstrap authors should add this into their documentation or something..Narcotic
Same deal here, we changed over to generating our SASS and completely forgot about the js file itself.. This needs to be the top answer.. As our modal is always by default included just before the body close tag...Peradventure
Thanks! I upgraded from 3.3.5 to 3.3.7 and it worked.Gooseneck
Same was the issue with me, different versionsForlini
V
128

I have also encountered this problem and none of the solutions worked for me until i figured out i actually don't need a backdrop. You can easily remove the backdrop with the folowing code.

<div class="modal fade" id="createModal" data-backdrop="false">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4>Create Project</h4>
            </div>
            <div class="modal-body">Not yet made</div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

Note: the data-backdrop attribute needs to be set to false (other options: static or true).

Vivienviviene answered 30/10, 2014 at 11:7 Comment(7)
Brilliant! I also needed to require bootstrap - not sure why all of my other Bootstrap functionality works fine but I needed require to make modal work.Heads
Perfect !!! struggled for a day ..and u saved my another day. Thanks again.. +1 and cheersShipe
After carefully reading all solutions, I found this to be the most sensible one as of todays version of bootstrap and jQuery. Thank you.Pandurate
Thank you! This question has over 140k in views and I don't understand why bootstrap can't fix this. oh well, cheers.Bullbat
A Good solution! Altough backdrop is good for user experienceCytogenesis
Backdrop -1 is not worked for me, but this do works, thank you.Cammiecammy
You know the old saying, there are 2 hard things in computer science, cache invalidation and z-indexSickroom
K
68

I got it to work by giving a high z-index value to the modal window AFTER opening it. E.g.:

$("#myModal").modal("show");
$("#myModal").css("z-index", "1500");
Kenwrick answered 12/12, 2012 at 7:24 Comment(9)
Is it working (the man says it is), why you down vote? As I am looking it seems that it will.Smail
Yeah, can anyone please explain why this is a bad answer? Is it just that it's kind of hacky?Monjan
I don't understand the down votes. Yes, it's hacky but the other solutions didn't work for me so thought I'd contribute this to the people who don't mind using "hacky" solutions to just get the damn thing to work.Kenwrick
This was relevant insight to my particular issue putting a modal over a fullscreen element. +1Cruiser
I agree, if none of the "right" answers work for an individual, and the "wrong" answer works flawlessly, use the "wrong" answer. Didn't even try this, but +1 for putting up something "wrong" that works flawlessly for you and the others that benefited from it (4 + those offset by the negative votes ) instead of being stuck clueless when the "right" answer didn't work for their case.Septennial
a good reason to downvote would be because it doesn't work. (maybe it did with bootstrap 2.x?)Tequilater
Was a bootstrap 2 issue. Also, the issue was resolved in a subsequent release. Shouldn't downvote things just because they don't work for your specific use case. It'll prevent people providing answers that worked for their use case.Kenwrick
It is a bad answer because it is a hack and doesn't make any attempt to indicate this. Other answers say, "if nothing else works you could...". The reality is that the modal is very widely used across the web and should work if implemented correctly. Hacky answers don't help people to work out how to do things the correct way.Barouche
@AndrewDyster I was faced with the same problem (today) as the OP and I've looked at a lot of answers which helped to a certain point, but yours was the clincher. However, since I had 2 fixed elements inside 2 included files, I had to use a higher z-index than what you posted, but nonetheless it worked, cheers.Blowtube
G
46

Solution provided by @Muhd is the best way to do it. But if you are stuck in a situation where changing structure of the page is not an option, use this trick:

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" data-backdrop="false" style="background-color: rgba(0, 0, 0, 0.5);">
<div class="modal-dialog" role="document">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal"
                aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
            <h4 class="modal-title" id="myModalLabel">Modal title</h4>
        </div>
        <div class="modal-body">...</div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary">Save changes</button>
        </div>
    </div>
</div>

The trick in here is data-backdrop="false" style="background-color: rgba(0, 0, 0, 0.5);" by removing the default backdrop and create a dummy one by setting background color of the dialog itself with some alpha.

Update 1: As pointed out by @Gustyn that clicking on the background does not close the dialog as is expected. So to achieve that you have to add some java script code. Here is some example how you can achieve this.

$('.modal').click(function(event){
    $(event.target).modal('hide');
});
Groth answered 28/8, 2015 at 7:45 Comment(5)
This works except that clicking on the background does not close the dialog as is expected.Shriver
Krishnendu u are my hero. I came to work with doom and gloom in mind. 3 days before my final presentation to be facing this issue all of a sudden was nerve wrecking to say the least. U my friend deserve 100000 upvotes alas can only give u one :) have a wonderfuly blessed day.Somerville
When I try this, it doesn't cover the full background of the page - just the div element that the modal is declared in.Erdda
This is the best solution IMO. Don't get why Bootstrap didn't implement it this way to begin with.Odelia
This worked perfectly for bootstrap 5 as well.Darrel
J
31

The easiest solution I found, that worked for all my cases, was an answer in a similar post:

Here it is:

.modal {
  background: rgba(0, 0, 0, 0.5); 
}
.modal-backdrop {
  display: none;
}

Basically, the original backdrop is not used. Instead you use the modal as the backdrop. The result is that it looks and behaves exactly as the original should've. It avoids all the issues with z-indexes (for me changing z-index to 0 solved the issue, but created a new problem with my nav menu being between the modal and backdrop) and is simple.

Credit goes to @Jevin O. Sewaruth for posting the original answer.

Jecon answered 10/7, 2020 at 16:44 Comment(3)
This should really be an accepted answer!Buchmanism
A good solution but I think it has an alternative. data-backdrop="false"Beneficent
Problem with this is the backdrop no longer serves the purpose of disabling anything behind the modal from being clicked, which is many times desired.Sickroom
P
22

This would cover all modals without messing up any of the animations or expected behavior..

$(document).on('show.bs.modal', '.modal', function () {
  $(this).appendTo('body');
});
Protect answered 5/8, 2017 at 4:22 Comment(6)
global solution. however it's better to find the problem.Motherland
I don't think is a great solution, what about pages with lots of modals? Could get messy.Gylys
Can you explain how it would get messy? All it's doing is moving the modal from where it currently is in the DOM to the end of the body tag. It's not creating anything that's not already there, just moving it and automatically giving it the top z-index.Protect
Best Solution i think. no need to edit any css and change modal appearanceEnlighten
This worked perfectly for me as I was not able to change my models because of the limitation of ng-repeat. It works for anyone that cannot change the structure of the page due to specific reasons (such as mine)Croat
#1 underrated answerCommemoration
H
16

A but late on this but here is a generic solution -

    var checkeventcount = 1,prevTarget;
    $('.modal').on('show.bs.modal', function (e) {
        if(typeof prevTarget == 'undefined' || (checkeventcount==1 && e.target!=prevTarget))
        {  
          prevTarget = e.target;
          checkeventcount++;
          e.preventDefault();
          $(e.target).appendTo('body').modal('show');
        }
        else if(e.target==prevTarget && checkeventcount==2)
        {
          checkeventcount--;
        }
     });

Visit this link - Bootstrap 3 - modal disappearing below backdrop when using a fixed sidebar for details.

Howitzer answered 15/1, 2014 at 1:15 Comment(1)
This was a perfect solution for a Wordpress plugin I was creating where I couldn't control the parent elements on other people's themes.Inviting
V
11

An other way to approach this is to remove the z-index from the .modal-backdrop in bootstrap.css. This will cause the backdrop to be on the same level as the rest of your body (it will still fade) and your modal to be on top.

.modal-backdrop looks like this

.modal-backdrop {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: #000000;
}
Vitellin answered 26/11, 2014 at 1:41 Comment(0)
L
11

Just add two lines of CSS:

.modal-backdrop{z-index: 1050;}
.modal{z-index: 1060;}

The .modal-backdrop should have 1050 value to set it over the navbar.

Laetitia answered 28/5, 2016 at 21:51 Comment(1)
Nice, but if the container of the modals has position: fixed this will not work.Manassas
T
9

I've simply set:

#myModal {
    z-index: 1500;
}

and it works....

For the original question:

.my-module {
    z-index: 1500;
}
Tarah answered 12/2, 2015 at 16:2 Comment(1)
My issue was the z-index too.Dinnie
K
9

I resolved my issue by adding data-backdrop="false" to the div:

<div class="modal fade" id="exampleModalCenter" data-backdrop="false" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">

.....
Korn answered 21/5, 2020 at 4:55 Comment(0)
P
9

The easiest solution is to move the modal dialog outside of any container and just declare it under the <body> element:

<body>    
    <div>
        ...
    <div>
    
    
    <div class="modal">
        ... modal dialog here
    </div>
</body>

I've tried this solution and it works for me.

Source: https://weblog.west-wind.com/posts/2016/sep/14/bootstrap-modal-dialog-showing-under-modal-background

Percutaneous answered 25/9, 2021 at 19:37 Comment(0)
V
8

Use this in your modal:

data-backdrop="false" 
Velamen answered 14/5, 2015 at 10:14 Comment(0)
D
8

This problem can often be experienced when using things like gradients in CSS for things like backgrounds or even accordion headers.

Unfortunately, modifying or overriding core Bootstrap CSS is undesirable, and can lead to unwanted side effects. The least intrusive approach is to add data-backdrop="false" but you may notice that the fade effect no longer works as expected.

After following recent releases of Bootstrap, version 3.3.5 seems to resolve this issue with no unwanted side effects.

Download: https://github.com/twbs/bootstrap/releases/download/v3.3.5/bootstrap-3.3.5-dist.zip

Be sure to include the CSS files and JavaScript files from 3.3.5.

Doall answered 10/9, 2015 at 4:10 Comment(0)
J
8

I have a lighter and better solution..

It could be easily solve through some additional CSS styles..

  1. hide the class .modal-backdrop (auto generated from Bootstrap.js)

    .modal-backdrop
    {
    display:none;
    visibility:hidden; 
    position:relative
    }
    
  2. set the background of .modal to a translucent black backdrop image.

    .modal
    {
    background:url("http://bin.smwcentral.net/u/11361/BlackTransparentBackground.png")
    // translucent image from google images 
    z-index:1100; 
    }
    

This will works best if you have a requirement that needs the modal to be inside an element and not near the </body> tag..

Jaclin answered 19/3, 2017 at 13:39 Comment(1)
you can view the edits here... stackoverflow.com/posts/42887253/revisionsCense
D
7

Hi I had the same issue then I realize that when you using bootsrap 3.1 Unlike in older versions of bootsrap (2.3.2) the html structure of the modal was changed!

you must wrap your modal header body and footer with modal-dialog and modal-content

<div class="modal hide fade">

  <div class="modal-dialog">
    <div class="modal-content">

    **here goes the modal header body and footer**

    </div>
  </div>

 </div>
Defray answered 12/2, 2014 at 8:22 Comment(3)
+1 make sure you are using compatible versions of bootstrap.css and bootstrap.js and that your markup matches the version you are using.Isabelisabelita
Yes this is what was my conclusion and I wrote it here just if anyone had this issue.Defray
Jesus Christ, this answer is buried deep. Same case for Bootstrap 4.Bushy
O
6

none of the suggested solutions above worked for me but this technique solved the issue:

$('#myModal').on('shown.bs.modal', function() {
   //To relate the z-index make sure backdrop and modal are siblings
   $(this).before($('.modal-backdrop'));
   //Now set z-index of modal greater than backdrop
   $(this).css("z-index", parseInt($('.modal-backdrop').css('z-index')) + 1);
}); 
Overdue answered 5/9, 2015 at 11:40 Comment(1)
I prefer this way because I lost CSS formatting with the other methods.Radiometeorograph
W
6

I had this issue and the easiest way to fix it was addind z-index greater than 1040 on the modal-dialog div:

<div class="modal-dialog" style="z-index: 1100;">

I believe bootstrap create a div modal-backdrop fade in which in my case has the z-index 1040, so if You put the modal-dialog on top of this, it should not be grey out anymore.

Wrestle answered 8/2, 2016 at 16:58 Comment(0)
C
5

in your navbar navbar-fixed-top need z-index = 1041 and also if u use bootstarp-combined.min.css the also change .navbar-fixed-top, .navbar-fixed-bottom z-index to 1041

Cycling answered 8/11, 2013 at 10:57 Comment(0)
M
5

set the z-index .modal to a highest value

For example, .sidebarwrapper has z-index of 1100, so set the z-index of .modal to 1101

.modal {
    z-index: 1101;
}
Mcvay answered 3/3, 2016 at 6:42 Comment(0)
R
5

In my case solve it, add this in my stylesheet:

.modal-backdrop{
  z-index:0;
}

with google debugger, can examine element BACKDROP And modify attributes. Goog luck.

Rainbolt answered 11/7, 2017 at 21:53 Comment(0)
G
4
$('.modal').insertAfter($('body'));
Guinevere answered 3/1, 2016 at 23:43 Comment(0)
D
4

This worked for me:

sass: 
  .modal-backdrop
    display: none
  #yourModal.modal.fade.in
    background: rgba(0, 0, 0, 0.5)
Delogu answered 1/10, 2017 at 7:57 Comment(0)
V
3

I removed modal backdrop.

.modal-backdrop {
    display:none;
}

This is not better solution, but works for me.

Violent answered 4/4, 2015 at 6:37 Comment(0)
C
3

You can also remove the z-index from .modal-backdrop. Resulting css would look like this.

.modal-backdrop {
}
  .modal-backdrop.in {
    opacity: .35;
    filter: alpha(opacity=35); }
Cirrate answered 5/5, 2015 at 20:38 Comment(0)
Z
3

what i find is that:

in bootstrap 3.3.0 it's not right,but when in bootstrap 3.3.5 it's right.let's see the code. 3.3.0:

this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />')
    .prependTo(this.$element)

3.3.5

  this.$backdrop = $(document.createElement('div'))
        .addClass('modal-backdrop ' + animate)
        .appendTo(this.$body)
Zygote answered 23/11, 2015 at 9:54 Comment(0)
M
3

Add this one to you pages. It work for me.

<script type="text/javascript">
    $('.modal').parent().on('show.bs.modal', function (e) { $(e.relatedTarget.attributes['data-target'].value).appendTo('body'); })
</script>
Mesonephros answered 23/7, 2016 at 12:50 Comment(0)
S
3

I was fixed this by adding style below to DIV tag

style="background-color: rgba(0, 0, 0, 0.5);"

And add custom css

.modal-backdrop {position: relative;}
Sentinel answered 5/10, 2016 at 3:48 Comment(0)
E
3

For me the easiest solution was to put my modal in a wrapper with absolute position and z-index higher than .modal-backdrop. Since modal-backdrop (at least in my case) has z-index 1050:

.my-modal-wrapper {
  position: absolute;
  z-index: 1060;
}
<div class="my-modal-wrapper"></div>
Elaboration answered 20/12, 2018 at 9:53 Comment(0)
Z
3

I went through my HTML and discovered I had an unclosed <div> tag. Closing the <div> resolved the issue for me. PS: The <div> tag was neither an ancestor nor a child of the modal.

Zosema answered 28/7, 2021 at 9:27 Comment(0)
J
2

In my case, I had a wrapper with the following:

.wrapper { margin: 0 auto; position:relative; z-index:1;overflow:hidden;}

Only removed the z-index:1 and have no idea why fixed the problem. also for sure removing the relative position did but I needed it.

Jd answered 21/3, 2014 at 7:4 Comment(0)
I
2

In my case, the cause was boostrap.min.css. Once I excluded it from my HTML file as a reference, the dialog showed in front of the modal shade.

Iggie answered 23/12, 2014 at 14:21 Comment(0)
L
2

Like Davide Lorigliola, I fixed it by cranking up the z-index:

.modal-backdrop { z-index: -999999; }
Langlois answered 6/5, 2015 at 1:45 Comment(0)
U
1

You can make a workaround but this will remove the fade from all the page. The modal will popup like Facebook popups. After opening the modal try:

 $('.modal-backdrop').removeClass('modal-backdrop');
Ultramarine answered 19/6, 2014 at 7:7 Comment(0)
E
1

This behaviour sometimes occurs when there is an unclosed tag, most especially an unclosed </div>. You can review where your modal is located and ensure all tags are properly closed or better yet move the div modal closer to the bottom of the page, imediately before </body> tag enclosure

Electrostatics answered 5/12, 2014 at 19:18 Comment(0)
P
1

Change the absolute position to relative.

.modal-backdrop {
    position: relative;
    /* ... */
}
Phlyctena answered 19/3, 2015 at 2:38 Comment(1)
it removes the black backgroundAllargando
C
1

I had same problem and also check Muhd's answer.

But, my modal needs left, top attribute, so just change fixed position to absolute and it worked.

.modal {
    position: absolute;
}
Complex answered 3/3, 2016 at 10:40 Comment(0)
E
1

CAREFUL WHEN APPENDING TO THE BODY!

This will definitely get that modal from behind the backdrop:

$('#myModal').appendTo("body").modal('show');

However, this adds another modal to the body each time you open it, which can cause head aches when adding controls like gridviews with edits and updates within update panels to the modal. Therefore, you may consider removing it when the modal closes:

For example:

$(document).on('hidden.bs.modal', function () {
        $('.modal').remove();
    });

will remove the the added modal. (of course that's an example, and you might want to use another class name that you added to the modal).

And as already stated by others; you can simply turn off the back-drop from the modal (data-backdrop="false"), or if you cannot live without the darkening of the screen you can adjust the .modal-backdrop css class (either increasing the z-index).

Elmerelmina answered 5/10, 2016 at 16:24 Comment(0)
L
1

I simply removed the position: fixed style from the _modal.scss file and it seems to work fine for me. I still have the background and it works as expected.

// Modal background
.modal-backdrop {
  /* commented out position: fixed - bug fix */
  //position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: $zindex-modal-backdrop;
  background-color: $modal-backdrop-bg;
  // Fade for backdrop
  &.fade {
    opacity: 0;
  }

Kudos to Rick Strahl for the guidance in "Bootstrap Modal Dialog showing under Modal Background".

Ligate answered 29/3, 2018 at 16:22 Comment(0)
T
1

I had the similar issue only for iOS devices.

Solution was by removing -webkit-overflow-scrolling: touch from parent element

Transilient answered 12/4, 2019 at 9:52 Comment(3)
why is this the case? i need the styleIrrawaddy
@Irrawaddy what you mean ?Transilient
I need access to the style -webkit-overflow-scrolling: touch but it's preventing my modals from being clickable in mobile browsersIrrawaddy
P
1

The solution is to put the modal directly under the body tag. If that is not possible for some reason then just add a overflow: visible property to the tag enclosing the modal, or use the following code:

<script>
    $(document).on('show.bs.modal', '.modal', function () {
        $('.div-wrapper-for-modal').css('overflow', 'visible');
    });

    $(document).on('hide.bs.modal', '.modal', function () {
        $('.div-wrapper-for-modal').css('overflow', 'auto');
    });
</script>
<div class="div-wrapper-for-modal">
    <div class="modal hide fade">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            <h3>Modal header</h3>
        </div>
        <div class="modal-body">
            <p>One fine body…</p>
        </div>
        <div class="modal-footer">
            <a href="#" class="btn">Close</a>
            <a href="#" class="btn btn-primary">Save changes</a>
        </div>
    </div>
</div>
Phillida answered 16/9, 2019 at 5:29 Comment(0)
P
1

Check your css to see if you have any blurs and filters. I removed this code from my css and the modal worked normally again

.modal-open .main-wrapper {
    -webkit-filter: blur(1px);
    -moz-filter: blur(1px);
    -o-filter: blur(1px);
    -ms-filter: blur(1px);
    filter: blur(1px);
}

Predecease answered 13/8, 2020 at 14:13 Comment(0)
L
1

Having

transform:translate3d(0, 0, 0);

On any ancestor element can cause this as well. Tested on bootstrap 4.6.0.

Leif answered 5/2, 2021 at 12:41 Comment(0)
F
1

Adding this in CSS made the trick for me.

.modal-backdrop.fade.show{
   z-index:0;
}
Faubourg answered 27/12, 2022 at 15:48 Comment(0)
W
1
  1. Use position absolute
.modal {
      display: none; /* Hidden by default */
      position: absolute; /* is positioned relative to the nearest positioned ancestor and moves along with page scrolling. */  
      padding-top: 10px; 
      left: 0;
      right:0; /* Full width (left and right 0) */
      top: 0;
      bottom: auto; /* Full height top and bottom 0 */
      overflow: auto; /* Enable scroll if needed */
      background-color: rgb(0,0,0); 
      background-color: rgba(0,0,0,0.5); 
      z-index: 9999 !important; 
    }
  1. Move the modal div so that it is outside any elements with special positioning. You can place it just before the closing body tag .
Wong answered 28/3, 2023 at 21:22 Comment(0)
M
1

For Bootstrap 5, use "data-bs-backdrop"

<div class="modal" id="myModal" data-bs-backdrop="false">
Midday answered 15/11, 2023 at 20:57 Comment(0)
D
0

Try overwriting the class .modal-open overflow value from hidden to visible:

.modal-open {
    overflow: visible;
}
Dahl answered 9/8, 2013 at 23:19 Comment(1)
A good answer should be explained. Saying, "try this" does not help the OP know what is going on. It might also work for reasons unrelated to the original problem except if you explain why.Barouche
I
0

I had some problem like this on Iphone and Ipad using Sharepoint 2013 Modal bootstrap keep z-index problems with backdrop.

I just use this on JS :

$('#myModal').on('shown.bs.modal', function() {
   //To relate the z-index make sure backdrop and modal are siblings
   $(this).before($('.modal-backdrop'));
   //Now set z-index of modal greater than backdrop
   $(this).css("z-index", parseInt($('.modal-backdrop').css('z-index')) + 1);
}); 
Incomputable answered 8/6, 2017 at 13:20 Comment(1)
What would be the question?Interlope
P
0
function addclassName(){
    setTimeout(function(){
        var c = document.querySelectorAll(".modal-backdrop");
        for (var i = 0; i < c.length; i++) {
            c[i].style.zIndex =  1040 + i * 20  ;
        }
        var d = document.querySelectorAll(".modal.fade");
        for(var i = 0; i<d.length; i++){
            d[i].style.zIndex = 1050 + i * 20;
        }
    }, 10);
}
Pyatt answered 29/8, 2017 at 9:28 Comment(1)
It helps more if you supply an explanation why this is the preferred solution and explain how it works. We want to educate, not just provide code.Terryl
H
0

According to the previous answers this could happen for several reasons. For me the problem was referencing two different Bootstrap links without knowing, so removing one solves the problem.

In my case I included this one:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.5/css/bootstrap.min.css"
      integrity="sha384-AysaV+vQoT3kOAXZkl02PThvDr8HYKPZhNT5h/CXfBThSRXQ6jW5DO2ekP5ViFdi" crossorigin="anonymous">

and another offline one that I have already in my laptop.

Hendrika answered 29/8, 2017 at 17:21 Comment(0)
S
0

For those like me that added Bootstrap to Wordpress without the use of plugin or theme:

I added bootstrap CSS and JS in the function.php file. Then, called the modal in a wordpress page. No matter what I did, the .modal-backdrop kept being in fron of #mymodal. I found out that it was a z-index problem but, as #mymodal was generated inside the content div and .modal-backdrop at the end of <body>, z-index couldn't work. What I did was moving #mymodal to the end of as well after it was generated:

$(document).ready(function () {
   $('#mymodal').on('shown.bs.modal', function () {
       $('#mymodal').appendTo(document.body);
     })
});

By the way, I had to add shown.bs.modal inside $(document).ready because it wasn't being called when I hit the button.

Sweeping answered 5/6, 2020 at 0:48 Comment(0)
P
0
.modal-backdrop {
/* bug fix - no overlay */    
display: none;}
Patman answered 7/6, 2020 at 19:23 Comment(2)
It helps more if you supply an explanation why this is the preferred solution and explain how it works. We want to educate, not just provide code.Terryl
It works though so a thank you won't harm, I can't teach basic css here mate :) That piece of code overides nested elements (including modals), threfore should work when the above issue appears.Patman
E
0

In my case the solution was simply that I forgot to add the "modal" class on the div with id "my-modal" that was promoted by $('#my-modal').modal('show');

Since the content of the div had everything required, the result on screen was almost perfect apart from that overlay above.

I would bet that the other answers with z-index trick or other css tricks that were not about positioning of parent divs or unclosed divs may have been in that case too.

Erect answered 25/3, 2022 at 14:16 Comment(0)
S
0

I encountered this problem when using with Angular 14, and i solved with change .modal-backdrop, from position: fixed; to position: relative;

::ng-deep.modal-backdrop {
  --bs-backdrop-zindex: 1050;
  --bs-backdrop-bg: #000;
  --bs-backdrop-opacity: 0.5;
  position: relative;
  top: 0;
  left: 0;
  z-index: var(--bs-backdrop-zindex);
  width: 100vw;
  height: 100vh;
  background-color: var(--bs-backdrop-bg);
}

Sexdecillion answered 28/8, 2022 at 8:6 Comment(0)
S
0

Just do this inside your css

.modal-dialog{
   pointer-events: auto;
}

NB: This property prevent modal-dialog container and all its child to be selected.

Salicaceous answered 12/3, 2023 at 12:26 Comment(0)
C
0

We just can add z-index by capturing backdrops created after the first

$(document).on("click", `[data-bs-toggle="modal"]`, function(){
    let backdrop = $(".modal-backdrop");
    if(backdrop.length > 1){
        backdrop.not(backdrop.first()).css("z-index", "3");
    }
});
Cristiano answered 12/6, 2023 at 8:25 Comment(0)
H
0

Add the above CSS class and it will work:

.modal-backdrop {
  position: fixed;
  top: 0;
  left: 0;
  z-index: -1;
}
Hardesty answered 3/8, 2023 at 8:27 Comment(0)
P
0

it is worked for me for bootsrap 5.0

$(document).on('shown.bs.modal', function (e)
 {
    
     var modal_backdrop = 109;
     var modal = 110;

     $('.modal-backdrop').each(function (i, obj)
     {
         $(this).css({ "z-index": modal_backdrop });
         modal_backdrop += 2;
     });

     $('.modal').each(function (i, obj)
     {
         $(this).css({ "z-index": modal });
         modal += 2;
     });



 });
Pshaw answered 5/1 at 20:32 Comment(0)
E
-1

Make Opacity to 1

.modal{
opacity:1;    
}
Earful answered 2/12, 2019 at 12:38 Comment(0)
A
-1

Update: The original JS method resulted in multiple clones of my modal being appended to the body, if the component is initialized multiple times. Instead, first confirm that the modal is not already appended:

function AttachModalsToBody(modalID) {
    var modal = $("body").children('#' + modalID);
    if ($("body").children('#' + modalID).length == 0) {
        $('#' + modalID).appendTo("body");
    }
}

In Blazor (where I make use of Bootstrap 5.0) I do the following (adapted from the answer of @AdamAlbright) to prevent the modal from appearing behind the backdrop:

In my project, each modal is inside its own separate component, and as I need to set their parameters from within other components, it's obviously not possible to move the modals outside of these parent components. I therefore use JS Interop to attach each modal to the body, when it renders for the first time.

Example: MyModal.razor

Inside each modal/component:

@inject IJSRuntime jsRuntime

<!--HTML Section omitted for brevity-->

    @code{
        protected override async Task OnAfterRenderAsync(bool firstRender)
        {
            if (firstRender)
                await jsRuntime.InvokeVoidAsync("AttachModalToBody", "#myModalID");
        }
    }

And inside JS file:

function AttachModalToBody(modalID) {
    $(modalID).appendTo("body");
}
Arjun answered 15/5, 2022 at 20:36 Comment(0)
S
-2

I found that by adding an inline style tag to set "display: none" prevented this problem. The position of the code did not have any effect.

Scaliger answered 30/9, 2013 at 16:52 Comment(1)
You haven't said what this was added to and why this would be a workable solution rather than a random hack that happens to work in your case.Barouche
S
-2

Try this code to CSS.

.modal-open { overflow: hidden !important; }
.modal-open *{ position:unset; z-index: 0; }
.modal-open .modal-backdrop { position: fixed; z-index: 99998 !important; }
.modal-open .modal { position: fixed; z-index: 99999 !important; }

Ex:

    $(window).on('load', function() {
      
/* Latest compiled and minified JavaScript included as External Resource */
$(document).ready(function() { $('.modal').modal("show"); });

    });
/* Optional theme */
@import url('//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-theme.min.css');

body {
    margin: 10px;
    padding-top: 50px;
}

.my-module {
    position: fixed;
    top: 0;
    left: 0;
    border: 1px solid red;
}

.modal-open { overflow: hidden !important; }
.modal-open *{ position:unset; z-index: 0; }
.modal-open .modal-backdrop { position: fixed; z-index: 99998 !important; }
.modal-open .modal { position: fixed; z-index: 99999 !important; }
<html><head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>Bootstrap 3 Template</title>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <meta name="robots" content="noindex, nofollow">
  <meta name="googlebot" content="noindex, nofollow">
  <meta name="viewport" content="width=device-width, initial-scale=1">


  <script type="text/javascript" src="//code.jquery.com/jquery-compat-git.js"></script>
    <link rel="stylesheet" type="text/css" href="/css/normalize.css">

    <link rel="stylesheet" type="text/css" href="/css/result-light.css">

      <script type="text/javascript" src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
      <link rel="stylesheet" type="text/css" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">


</head>
<body class="modal-open">
    <div class="container">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus et augue sed lorem laoreet vehicula sit amet eget tortor. Donec in turpis gravida, commodo mauris ac, gravida neque. Proin eget tristique lorem. Integer tincidunt sem sit amet metus ultricies, vitae placerat dui gravida. Pellentesque viverra, nunc imperdiet egestas imperdiet, magna massa varius arcu, vitae iaculis tortor quam vitae arcu. Fusce posuere non lectus vel cursus. In rutrum sed dui non sollicitudin. Proin ante magna, imperdiet ac nisl ut, rhoncus pellentesque tortor.</p>

    <p>Cras ac velit vitae elit tempus tempus. Nullam eu posuere leo. In posuere, tortor et cursus ultrices, lorem lacus efficitur dolor, a aliquet elit urna sed tortor. Donec dignissim ante ex, non congue ex efficitur sit amet. Suspendisse lacinia tristique odio, vel sagittis dui tempor tempus. Quisque gravida mauris metus, sed aliquam lacus sollicitudin sit amet. Pellentesque laoreet facilisis scelerisque. Nunc a pulvinar magna. Maecenas at mollis tortor.</p>

    <p>Vivamus ultricies, odio sed ornare maximus, libero justo dignissim nulla, nec pharetra neque nulla vel leo. Donec imperdiet sem sem, eu interdum justo tincidunt finibus. Vestibulum lacinia diam gravida risus luctus, elementum blandit dui porttitor. Quisque varius lacus et tempor faucibus. Nam eros nunc, gravida eu tellus eget, placerat porta leo. Duis tempus ultricies felis sit amet cursus. Nunc egestas ex non lacus laoreet tincidunt. Sed malesuada placerat elementum. Mauris eu rutrum nulla. Nunc consequat lacus eget libero tincidunt, in semper eros accumsan. Interdum et malesuada fames ac ante ipsum primis in faucibus. Suspendisse eu tincidunt quam, ut tincidunt eros. Donec luctus velit ac nulla lacinia malesuada.</p>

    <p>Vestibulum id mi in urna lacinia mollis. Pellentesque sit amet mauris ullamcorper, suscipit dolor in, lacinia leo. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; In hac habitasse platea dictumst. Vivamus sollicitudin tempus massa sed molestie. Nullam quis neque vel nunc convallis porta a laoreet ex. Aliquam tempus hendrerit turpis eleifend convallis. Cras enim eros, fermentum sed velit eget, dignissim malesuada augue. Fusce ut fermentum nisl, vel imperdiet libero. Etiam luctus arcu volutpat turpis finibus pulvinar eget in augue. Integer sapien nisi, scelerisque ultrices quam sit amet, aliquam placerat neque. Morbi consequat porttitor lacus, quis pulvinar dolor aliquam ut. Ut et dolor id est iaculis lobortis nec aliquet nisl.</p>

    <p>Nunc et tortor cursus, ullamcorper justo vitae, ullamcorper sapien. In fringilla urna quam, et finibus ipsum finibus eu. In fermentum turpis ut eros semper, non gravida purus ornare. Praesent vehicula lobortis lacinia. Vivamus nec elit libero. Suspendisse porta neque ut erat tempor rhoncus. Nunc quis massa in ante rhoncus bibendum. Nam maximus ex vitae orci luctus scelerisque. Sed id mauris iaculis, scelerisque mauris feugiat, vehicula ipsum. Duis semper erat ac nulla sodales gravida. Suspendisse nec sapien pharetra, scelerisque odio in, dignissim erat. Aenean feugiat sagittis eros, in mattis orci tristique lacinia. Phasellus posuere id neque sed mattis. Morbi accumsan faucibus ullamcorper.</p>    
    
    
<div class="my-module">
    This is a container for "my-module" with some fixed position. The module contains the modal code.
<div class="modal fade in" aria-hidden="false" style="display: block;">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
        <h4 class="modal-title">Modal title</h4>
      </div>
      <div class="modal-body">
        <p>One fine body…</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
    
</div>
</div>
</body></html>
Shamrock answered 14/3, 2019 at 8:50 Comment(0)
W
-2

For Angular:

($('.modal-backdrop') as any).remove();
Wylde answered 6/5, 2021 at 13:22 Comment(2)
Hi, try to add some more explaination to your answerExtensor
This will remove the backdrop @T.Czubaszek. We don't want the modal backdrop to be removed and instead take care of how the elements are positioned using z-index. Make sure that the dialog has a z-index more than any content belowMichell
E
-3

Remove modal-backdrop background which is set to black in your bootstrap CSS

See mine:

.modal-backdrop {
    position: fixed; /*---- commented and it shows */
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 1030;
    /*background-color: #000000; */
}

and then add this background color and opacity of o.5. see mine:

.modal-backdrop {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 1030; 
  background-color: rgba(0, 0, 0, 0.5);
  opacity: 0.5;

}

NOTE: Though these changes were made in the boostrap css, I used angular-strap and I didn't download or use the ng-animate css

Electromagnetism answered 3/7, 2014 at 22:19 Comment(2)
This is not a solution. The OP wants to know why it isn't working, not how to hack out of it by changing CSS.Barouche
Agreed, it's a way to get the desired result, but involves changing the bootstrap CSS which isn't ideal.Roderick
O
-4

Add this to your style sheet:

.modal-backdrop {
    background-color: #000;
    bottom: 0;
    left: 0;
    position: fixed;
    right: 0;
    top: 0;
    z-index: 0 !important;
}
Oration answered 25/11, 2014 at 10:40 Comment(1)
No explanation as to what this does and why it is an acceptable solution. Other answers already explain the types of actual causes of this and don't require hacks.Barouche

© 2022 - 2024 — McMap. All rights reserved.