IE 6 & IE 7 Z-Index Problem - css

http://madisonlane.businesscatalyst.com
I'm trying to get the div#sign-post to sit above the div#bottom. This works fine in all browsers except IE6 & IE7. Can anyone see what the problem is here?
Also IE6 is displaying an additional 198px to the top of div#bottom.

Most of the answers here are wrong; some work, but not for the reason they state. Here is some explanation.
This is how z-index should work according to the spec:
you can give a z-index value to any element; if you don't, it defaults to auto
positioned elements (that is, elements with a position attribute different from the default static) with a z-index different from auto create a new stacking context. Stacking contexts are the "units" of overlapping; one stacking context is either completely above the another (that is, every element of the first is above any element of the second) or completely below it.
inside the same stacking context, the stack level of the elements is compared. Elements with an explicit z-index value have that value as a stack level, other elements inherit from their parents. The element with the higher stack level is displayed on top. When two elements have the same stack level, generally the one which is later in the DOM tree is painted on top. (More complicated rules apply if they have a different position attribute.)
In other words, when two elements have z-index set, in order to decide which will show on top, you need to check if they have any positioned parents which also have z-index set. If they don't, or the parents are common, the one with the higher z-index wins. If they do, you need to compare the parents, and the z-index of the children is irrelevant.
So the z-index decides how the element is placed compared to other children of its "stacking parent" (the closest ancestor with a z-index set and a position of relative, absolute or fixed), but it doesn't matter when comparing to other elements; it is the stacking parent's z-index (or possibly the z-index of the stacking parent's stacking parent, et cetera) which counts. In a typical document where you use z-index only on a few elements like dropdown menus and popups, none of which contains the other, the stacking parent of all the elements which have a z-index is the whole document, and you can usually get away with thinking of the z-index as a global, document-level ordering.
The fundamental difference with IE6/7 is that positioned elements start new stacking contexts, whether they have z-index set or not. Since the elements which you would instinctively assign z-index values to are typically absolutely positioned and have a relatively positioned parent or close ancestor, this will mean that your z-index-ed elements won't be compared at all, instead their positioned ancestors will - and since those have no z-index set, document order will prevail.
As a workaround, you need to find out which ancestors are actually compared, and assign some z-index to them to restore the order you want (which will usually be reverse document order). Usually this is done by javascript - for a dropdown menu, you can walk through the menu containers or parent menu items, and assign them a z-index of 1000, 999, 998 and so on. Another method: when a popup or dropdown menu becomes visible, find all its relatively positioned ancestors, and give them an on-top class which has a very high z-index; when it becomes invisible again, remove the classes.

Agree with validator comment - validating usually helps. But, if it doesn't heres a few pointers for z-index in IE:
1) elements who's z-index you're manipulating should be on the same level ie. you should be setting the z-index of #bottom and #body
if this is not feasible then
2) IE sometimes wont apply the z-index correctly unless the elements ou are applying it to have a position:relative. Try applying that property to #bottom and #body (or #signpost)
let me know how that works out
Darko

I just had this problem and the fix I found (thanks to Quirksmode) was to give the direct parent of the node you are trying to set a z-index of it's own z-index that is at less than the z-index of the node you are trying to set. Here is a quick example that should work in IE6
<html>
<head>
<style type="text/css">
#AlwaysOnTop {
background-color: red;
color: white;
width: 300px;
position: fixed;
top: 0;
z-index: 2;
}
#Header {
color: white;
width: 100%;
text-align: center;
z-index: 1;
}
</style>
</head>
<body>
<div id="Header">
<div id="AlwaysOnTop">This will always be on top</div>
</div>
<div id="Content">Some long amount of text to produce a scroll bar</div>
</body>
</html>

Welcome, I solved the problem with:
.header {
position: relative;
z-index: 1001;
}
.content {
position: relative;
z-index: 1000;
}

Looks to me like you have some malformed HTML in there. I tried counting, and perhaps I lost count of the opening and closing tags, but it looks like div#container isn't closed. Try running your page through a validator (such as W3C's HTML Validator, or something) and fixing some of the errors. That's helped me with these sorts of problems in the past. Good luck!

I've recently had an ongoing problem displaying one layer above another. In my case I was programmatically creating two layers in Javascript, one for diaplaying a custom control and one for creating a full screen layer behind it. FF was fine, bu IE displayed the full screen layer always on top of everything else.
After numerous trawls over the interweb, trying everyone's suggestions, the only way I eventually get it working was to remove position: attributes from both layers, and tweak the margin-top: attribute until I got a satisfactory result.
A bit of a hash, but it works and it'll be fine until IE 8 sorts out all of the current bugs......

the only reliable solution is, to put the top elements below in the code and then push them over the other stuff with absolute positioning.
e.g. Wordpress:
put the navigation in the footer file, but still inside the page wrapper.
might also bring some advantages for search engines, because they can directly start with the content, without crawling through the menu first...
UPDATE:
I need to correct myself. While putting the element below and then pushing it over is still the easiest way, there are certain cases when this is not possible in reasonable time. Then you have to make sure that each and every parent element has some kind of positioning and some senseful z-index. Then the z-index should work again even in IE7.

Related

How to make a Div appear on top of everything else on the screen? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Edit to reopen:
It seems to be difficult to position elements over a google map. Using z-index does not solve the problem which is described below: Google Maps will stay on top of some other elements even when using high z-indexes.
The question is:
Is it possible to have a div cover parts of a google map?
I have the following popup:
But when i move this popup up to appear over the map, it gets hidden:
How to force something to be the top most, always displayed object on screen?
I have tried setting the z-index on my CSS property sheet, but this did not work.
Is there some HTML/CSS property i can set so that the popup, which is a DIV, actually always sets on top of everything else?
z-index is not that simple friend. It doesn't actually matter if you put z-index:999999999999..... But it matters WHEN you gave it that z-index. Different dom-elements take precedence over each other as well.
I did one solution where I used jQuery to modify the elements css, and gave it the z-index only when I needed the element to be on top. That way we can be sure that the z-index of this item has been given last and the index will be noted. This one requires some action to be handled though, but in your case it seems to be possible.
Not sure if this works, but you could try giving the !important parameter too:
#desired_element { z-index: 99 !important; }
Edit: Adding a quote from the link for quick clarification:
First of all, z-index only works on positioned elements. If you try to set a z-index on an element with no position specified, it will do nothing. Secondly, z-index values can create stacking contexts, and now suddenly what seemed simple just got a lot more complicated.
Adding the z-index for the element via jQuery, gives the element different stacking context, and thus it tends to work. I do not recommend this, but try to keep the html and css in a such order that all elements are predictable.
The provided link is a must read. Stacking order etc. of html elements was something I was not aware as a newbie coder and that article cleared it for me pretty good.
Reference philipwalton.com
Try setting position to absolute, ie.
#yourDiv{
position: absolute;
z-index: 10;
};
Are you using position: relative?
Try to set position: relative and then z-index because you want this div has a z-index in relation with other div.
By the way, your browser is important to check if it working or not. Neither IE or Firefox is a good one.
you should use position:fixed to make z-index values to apply to your div
Set the DIV's z-index to one larger than the other DIVs. You'll also need to make sure the DIV has a position other than static set on it, too.
CSS:
#someDiv {
z-index:9;
}
Read more here: http://coding.smashingmagazine.com/2009/09/15/the-z-index-css-property-a-comprehensive-look/
One form to do this is insert the panel that you want to expand inside a DIV setted as relative: let me show you:
<div style="position:relative">
<div style="position:absolute; z-index: 1000;">
your code
</div>
</div>
You use the first div to position the inner content in a specific area inside your page and the second absolute should be referred to the container (because is relative) The z-index in this case is referred also to container and if it higher that the container should be at top. You can put the style in a CSS class and change the size of the absolute div to expand it on hover or another action that you want to control.
I hope that this help
dropdowns always show up on top, only solution for this problem is to hide dropdowns when image is displayed (display:block or visibility:visibile) and show them when image hidden (display:none or visibility:hidden)

Clean CSS fix of IE7's 'float: right' drop bug

I continuously find myself having problems with elements floated right in IE7.
I have read many Stack Overflow questions which are similar to this one but there doesn't seem to be any consistently clean CSS answers.
What I mean by this is is I want to see answers which DO NOT change the HTML. E.g:
Put the floated element first
Add a 'clear: both' div after the floated element.
I understand that sometimes the floated element doesn't account for its parents height and therefore sometimes fails to contain it properly. Occasionally I find myself 'adding layout' to an element with zoom: 1 which sometimes fixes it. Other times I find myself messing about in a conditional IE7 style-sheet which isn't the best fix in my opinion.
Note: What I mean by 'having layout' - http://www.satzansatz.de/cssd/onhavinglayout.html
I have also read other answers to do with using relative and absolute positioning (parent div and child div respectively). This pulls it up but often affects surrounding divs.
I would be happy to add a bounty to this question if someone can give an in depth explain as to the reasons this happens and a detailed discussion of the various fixes, IDEALLY CSS ONLY!
Many thanks!
EDIT
The most common problem I encounter is when I have something like this:
Left Sidebar - Main - Right Sidebar
Right will often drop when floated. Ideally this should be in the format Left - Right - Main, but I continuously find myself styling developers work (Drupal mainly) where this is the case and it is too much hassle to get them to change their work. Make sense? Because I'm styling developers work they never put the clear block in too (which personally I think is horrible and dirty anyways!)
Introduction
Your title indicates a desire to see a fix for the float: right drop bug, but your text implies some broader scope desire to see solutions to “problems with elements floated right in IE7.” There are many general problems with floated elements (right or left) in that browser. Even though one may question whether support of the IE7 browser is worthy of much attention any more, it undoubtedly will remain so for some people for some time. Therefore, I’m going to take the opportunity here to address numerous issues at once regarding floats in that browser. Note that many experiments and references below come from an excellent resource: http://www.brunildo.org/test/index.html.
CSS for the Containing Element
For a containing parent to the floated element the following css should be set:
.container {
overflow: auto; /* forces clearing of the child float */
zoom: 1; /* give it layout (this can be some other css that does likewise) */
}
Making sure it hasLayout is important to prevent types of margin and padding errors, a type of peek-a-boo bug, and allowing the overflow to clear. For a sequence of floats, some html may need changing if padding on the container is desired to work properly.
With regards to one “drop” issue with a float: right, you may want to avoid setting an explicit height or max-height on the container. A min-height is okay. Setting a height and then having the float be taller than the container makes IE7 not behave with following elements. There is no pure css solution that I have found noted.
If the container is itself position: absolute there can be issues with positioning a float that may require that float itself to be set to position: absolute instead of being floated.
References:
For overflow to clear -- http://www.quirksmode.org/css/clearing.html
Margins -- http://www.brunildo.org/test/IEFloatAndMargins.html
Peek-a-boo -- http://www.brunildo.org/test/iew_boo.html and http://www.brunildo.org/test/iew_boo3.html
Float sequence padding -- http://www.brunildo.org/test/IEmfloa.html
Avoiding height -- http://austinmatzko.com/2007/07/25/internet-explorer-7-float-bug/, http://www.brunildo.org/test/fenc7.html (and his similar problem link on that page).
Container is absolute -- Floating Too Far Right!
CSS for the Floated Child
For a the floated child element, the css (besides float: right) to set depends on two things:
Absolute Container
Again, as noted above, a containing parent that is absolute may require a change in how the child is handled.
Float is Also a Clearing Element
If the float is also going to have a clear set on it, then there are numerous issues that can arise depending totally upon the html and css of the elements around it. There is no single canonical fix, so look at the references below.
References:
Container is absolute -- Floating Too Far Right!
Also having clear -- http://www.brunildo.org/test/IEWfc.html, http://www.brunildo.org/test/IEWfc2.html, http://www.brunildo.org/test/IEWfc3.html
CSS for Child Elements of Container Before the Float
If the float: right follows an element in the html structure that should be to its left (and not above it), then that preceding element(s) must be float: left.
CSS for Child Elements of Container After the Float
A Clear Element
For an element after the float that has clear set, then if it has padding and background-color, make sure it also hasLayout to avoid a doubling of the padding; also this prevents extra space above the clear due to container padding, and avoids other margin issues.
References:
For padding -- http://www.brunildo.org/test/IEClearPadding.html and http://www.brunildo.org/test/IEFloatClearPadding.html
For margins -- http://www.brunildo.org/test/Op7_margins_float.html (look down the page for IE7)
A Paragraph Before a Clear Element
Having a paragraph with a margin-bottom and shorter in height than the float, located between the floated element and a clearing element, can create an extra gap between the clear and the float equal to that margin. There is no known pure css fix other than giving the paragraph a zero bottom margin (which may not be acceptable if the paragraph may go taller than the float).
Reference:
Paragraph following -- http://www.brunildo.org/test/IEFloatClearMargin.html
Conclusion
I cannot guarantee I have addressed every issue that may occur with a right floated object, but certainly many major ones are covered. As to “why” these things happen, it is all “bugginess` in IE7.
Have you tried to use the clearfix solution to collapsing divs? There are variations on this and there is a newer version but I don't have the url to hand, but this is standard clearfix css which you add to the parent element that is collapsing and causing issues with floated elements http://www.webtoolkit.info/css-clearfix.html. Chris Coyer has a better version here http://css-tricks.com/snippets/css/clear-fix/.
You say "I understand that sometimes the floated element doesn't account for its parents height and therefore sometimes fails to contain it properly" this is kind of true, the parent will collapse if all child elements are floated. This is due to the elements being removed from the normal flow, when this occurs the parent div is unable to calculate its height and collapses as if there isn't anything inside of the div.
But without seeing the page and the issue you are having I can only estimate that the issue is due to IE6-IE7's haslayout property which is really annoying, they sorted it out from version 8 upwards but it does add extra development time to your build.
But in most situations the clearfix solution is best as it doesn't add extra markup to the page such as
<div style="clear: both"></div>
this is old and out of date and should be avoided.
I hope this helps you, if you need any more information or I have not answered the question just ask.
We have been using the clearfix solution for years now.
.cf:after { content: "."; display: block; clear: both; visibility: hidden; line-height: 0; height: 0; }
.cf { display: inline-block; }
html[xmlns] .cf { display: block; }
* html .cf { height: 1%; }
This is a simple CSS class which, ideally, has to be applied to a container that has any child float elements. Since you're restrictive about not changing the HTML at all, you can either:
replace all occurrences of .cf with your own div's selector [or]
use JS to apply the class (which is bad because users will see a broken layout a few seconds until the page loads completely) [or]
use PHP ob_start() + regex to apply the class [or]
just go vintage and rewrite everything using tables (as we used to do in the `90s)
It's simple:
Where you have float:right, add *clear:left.
Or where you have float:left, add *clear:right.
* for IE7-
Or for validation
*+html .class{clear:left/right}
I know it's been a year since this was posted, but I found a solution that I like for this. The gist is using 'expression' tag in your CSS for IE7 only to move the floated element to be the first element of the parent in the DOM. It will be semantically correct for all other browsers, but for IE7 we modify the DOM to move the floated element.
In my case, I have:
<div>
<h1></h1>...<p>any other content...</p>
<small class="pull-right"></small>
</div>
In my CSS for pull-right, I use:
.pull-right {
float:right;
*zoom: ~"expression( this.runtimeStyle.zoom='1',parentNode.insertBefore( this,parentNode.firstChild ))";
}
The result is that IE7 moves my <small> to be the first element of <div> but all other browsers leave the markup alone.
This might not work for everyone. Technically, it is modifying the markup but only in the DOM for IE7 and it's also a javascript solution.
Also, I understand there may be some performance issues with expression (it's slow), so perhaps it's not ideal there are a lot of floats like this. In my case, it worked well and allowed me to keep semantically correct HTML.

A depth (z-index) nightmare

The best way to illustrate this question is with...a Fiddle! Before you visit the fiddle, notice there is text behind the grayest element, which is on top of a light gray element that has a border.
There is a main wrapping div (root), and two wrapping divs inside (wrap1 and wrap2). The problem here is that I need the content of wrap2 (highlight) to be behind the content of wrap1 (text), but in front of the background of the root.
This, however, must not change:
The HTML, the elements and wraps should be left untouched. Excluding the order of wrap1 and wrap2 inside root.
The highlight div must keep the absolute positioning.
Styling highlight with background-color is not an option, the existence of highlight is a must.
PS: the italics reference the id's of <div>s in the fiddle example, for whomever was too lazy to visit it.
I was able to display the text in front of the highlight by adding a z-index to text. (Adding the z-index to wrap1 also works.) The trick is to remember that z-index doesn't apply to statically-positioned elements, so you need to give the same div position: relative.
#text {
position: relative;
z-index: 1000;
}
(Large z-index because I've been bitten by IE not respecting low values in the past. May or may not still be an issue. ;-)
z-index can be difficult to grasp. I think somebody already answered your question, but if you want to learn more how they work, this is a pretty comprehensive guide:
http://www.onextrapixel.com/2009/05/29/an-indepth-coverage-on-css-layers-z-index-relative-and-absolute-positioning/
And also, here is a link where you can try out different z-index and how they are affected by different position properties (the main reason for difficulty)
http://tjkdesign.com/articles/z-index/teach_yourself_how_elements_stack.asp
#wrap1{position:absolute;z-index:2;}

What has bigger priority: opacity or z-index in browsers?

I'm coding a "popup window" in JavaScript and I've come across an interesting thing:
The navy square under the popup window is visible even though I would expect it to be hidden. The popup was added after the square, so it should be on the top.
CSS opacity property of the navy square is 0.3. From what I've tried, it seems that every number from the interval (0,1) would yield the same result. If I change it to 1, then it behaves as expected (i.e. the part of the square under the popup is hidden).
I've tried to set the z-index property to 10 for the square and 100 for the popup, but it doesn't change anything.
What am I missing? Why is part of square displayed?
Tested browsers:
Firefox 3.6.x
Chrome 4
This is not a bug and is actually how it's supposed to work. It's a bit confusing as the elaborate description of Stacking Contexts doesn't mention anything about it. However, the visual formatting module links to the color module where this particular gotcha can be found (emphasis mine):
Since an element with opacity less than 1 is composited from a single
offscreen image, content outside of it cannot be layered in z-order
between pieces of content inside of it. For the same reason,
implementations must create a new stacking context for any element
with opacity less than 1. If an element with opacity less than 1 is
not positioned, implementations must paint the layer it creates,
within its parent stacking context, at the same stacking order that
would be used if it were a positioned element with ‘z-index: 0’ and
‘opacity: 1’. If an element with opacity less than 1 is positioned,
the ‘z-index’ property applies as described in [CSS21], except that
‘auto’ is treated as ‘0’ since a new stacking context is always
created. See section 9.9 and Appendix E of [CSS21] for more
information on stacking contexts. The rules in this paragraph do not
apply to SVG elements, since SVG has its own rendering model ([SVG11],
Chapter 3).
It's not a problem of opacity being more important than z-index, rather than z-index being relative to their stacking context (see z-index in the CSS2 specification).
In other words, z-index are only significant within the context of a positioned ancestor (whether its relative, absolute or fixed). What you need to do to fix your problem is add a position: relative; to the element that contain both your popup and your navy square, and probably add it a z-index: 1; . Seeing your screenshot it will probably be a top element such as a wrapper div.
Workaround for two elements, like divs: add a 0.99 opacity to your top element, and the order of both is reestablished.
opacity: 0.99;
An alternative to using opacity, is to use a transparent colour (with an alpha value)
So, rather than using
{
background: gray;
opacity: 0.5;
}
You could try
{
background: rgba(128,128,128,0.5);
}
It isn't identical, but I was encountering the same issue you were having, and the above fixed it.
Example code might be needed to debug this problem.
You might put overflow: hidden and possibly position: relative in a DIV which surrounds all the editor objects to try to force the elements to only be drawn within that DIV, e.g:
<div style="overflow: hidden; position: relative">
(Editor object buttons go here)
</div>
As a last resort, you could also try a iframe in between the two elements to try to stop them seeping through.
You might try to set the popup window's DIV like this using !important so the style doesn't change on applying new style or class:
background-color: white !important;
z-index: 100 !important;
opacity: 1.0 !important;
Then, make new CSS class:
.PopupElement
{
z-index: inherited;
opacity: inherited;
}
And add class to all elements in the window, like this for example:
<input value="posx" class="some_class PopupElement"/>
My guess is that this would work, since there is no priority in applying CSS attributes... as far as I know. =)
I had the same issue. Using rgba instead of color/opacity solved my problem. Working with LESS (in the Bootstrap framework), the fade() function did the conversion for me.
Although #Guillaume Esquevin already gave a great answer, I will try to expand on it in case someone ignores what a stacking context is (like I did).
As you can read here, there is something called stacking context, which refers to a group of elements sharing a parent that move together in the stack. An example could be a div and all its children.
There are three ways to create a stacking context: in the root of the document (the html element), by positioning the parent element, and by changing the opacity of the parent to something lower than 1.
Then, if you have a div with opacity lower than 1 and you want some sibling element of this div to appear behind it (and its children), you can create a new stacking context on such sibling by setting its position to relative or by changing its opacity as well.

What is the difference between visibility:hidden and display:none?

The CSS rules visibility:hidden and display:none both result in the element not being visible. Are these synonyms?
display:none means that the tag in question will not appear on the page at all (although you can still interact with it through the dom). There will be no space allocated for it between the other tags.
visibility:hidden means that unlike display:none, the tag is not visible, but space is allocated for it on the page. The tag is rendered, it just isn't seen on the page.
For example:
test | <span style="[style-tag-value]">Appropriate style in this tag</span> | test
Replacing [style-tag-value] with display:none results in:
test | | test
Replacing [style-tag-value] with visibility:hidden results in:
test |                        | test
They are not synonyms.
display:none removes the element from the normal flow of the page, allowing other elements to fill in.
visibility:hidden leaves the element in the normal flow of the page such that is still occupies space.
Imagine you are in line for a ride at an amusement park and someone in the line gets so rowdy that security plucks them from the line. Everyone in line will then move forward one position to fill the now empty slot. This is like display:none.
Contrast this with the similar situation, but that someone in front of you puts on an invisibility cloak. While viewing the line, it will look like there is an empty space, but people can't really fill that empty looking space because someone is still there. This is like visibility:hidden.
One thing worth adding, though it wasn't asked, is that there is a third option of making the object completely transparent. Consider:
1st unseen link.<br />
2nd unseen link.<br />
3rd unseen link.
(Be sure to click "Run code snippet" button above to see the result.)
The difference between 1 and 2 has already been pointed out (namely, 2 still takes up space). However, there is a difference between 2 and 3: in case 3, the mouse will still switch to the hand when hovering over the link, and the user can still click on the link, and Javascript events will still fire on the link. This is usually not the behavior you want (but maybe sometimes it is?).
Another difference is if you select the text, then copy/paste as plain text, you get the following:
1st link.
2nd link.
3rd unseen link.
In case 3 the text does get copied. Maybe this would be useful for some type of watermarking, or if you wanted to hide a copyright notice that would show up if a carelessly user copy/pasted your content?
display:none removes the element from the layout flow.
visibility:hidden hides it but leaves the space.
There is a big difference when it comes to child nodes. For example: If you have a parent div and a nested child div. So if you write like this:
<div id="parent" style="display:none;">
<div id="child" style="display:block;"></div>
</div>
In this case none of the divs will be visible. But if you write like this:
<div id="parent" style="visibility:hidden;">
<div id="child" style="visibility:visible;"></div>
</div>
Then the child div will be visible whereas the parent div will not be shown.
They're not synonyms - display: none removes the element from the flow of the page, and rest of the page flows as if it weren't there.
visibility: hidden hides the element from view but not the page flow, leaving space for it on the page.
display: none removes the element from the page entirely, and the page is built as though the element were not there at all.
Visibility: hidden leaves the space in the document flow even though you can no longer see it.
This may or may not make a big difference depending on what you are doing.
With visibility:hidden the object still takes up vertical height on the page. With display:none it is completely removed. If you have text beneath an image and you do display:none, that text will shift up to fill the space where the image was. If you do visibility:hidden the text will remain in the same location.
display:none will hide the element and collapse the space is was taking up, whereas visibility:hidden will hide the element and preserve the elements space. display:none also effects some of the properties available from javascript in older versions of IE and Safari.
visibility:hidden preserves the space; display:none doesn't.
In addition to all other answers, there's an important difference for IE8: If you use display:none and try to get the element's width or height, IE8 returns 0 (while other browsers will return the actual sizes). IE8 returns correct width or height only for visibility:hidden.
display: none;
It will not be available on the page and does not occupy any space.
visibility: hidden;
it hides an element, but it will still take up the same space as before. The element will be hidden, but still, affect the layout.
visibility: hidden preserve the space, whereas display: none doesn't preserve the space.
Display None Example:https://www.w3schools.com/css/tryit.asp?filename=trycss_display_none
Visibility Hidden Example : https://www.w3schools.com/cssref/tryit.asp?filename=trycss_visibility
visibility:hidden will keep the element in the page and occupies that space but does not show to the user.
display:none will not be available in the page and does not occupy any space.
display: none
It will remove the element from the normal flow of the page, allowing other elements to fill in.
An element will not appear on the page at all but we can still interact with it through the DOM.
There will be no space allocated for it between the other elements.
visibility: hidden
It will leave the element in the normal flow of the page such that is still occupies space.
An element is not visible and Element’s space is allocated for it on the page.
Some other ways to hide elements
Use z-index
#element {
z-index: -11111;
}
Move an element off the page
#element {
position: absolute;
top: -9999em;
left: -9999em;
}
Interesting information about visibility: hidden and display: none properties
visibility: hidden and display: none will be equally performant since they both re-trigger layout, paint and composite. However, opacity: 0 is functionality equivalent to visibility: hidden and does not re-trigger the layout step.
And CSS-transition property is also important thing that we need to take care. Because toggling from visibility: hidden to visibility: visible allow for CSS-transitions to be use, whereas toggling from display: none to display: block does not. visibility: hidden has the additional benefit of not capturing JavaScript events, whereas opacity: 0 captures events
If visibility property set to "hidden", the browser will still take space on the page for the content even though it's invisible.
But when we set an object to "display:none", the browser does not allocate space on the page for its content.
Example:
<div style="display:none">
Content not display on screen and even space not taken.
</div>
<div style="visibility:hidden">
Content not display on screen but it will take space on screen.
</div>
View details
There are a lot of detailed answers here, but I thought I should add this to address accessibility since there are implications.
display: none; and visibility: hidden; may not be read by all screen reader software. Keep in mind what visually-impaired users will experience.
The question also asks about synonyms. text-indent: -9999px; is one other that is roughly equivalent. The important difference with text-indent is that it will often be read by screen readers. It can be a bit of a bad experience as users can still tab to the link.
For accessibility, what I see used today is a combination of styles to hide an element while being visible to screen readers.
{
clip: rect(1px, 1px, 1px, 1px);
clip-path: inset(50%);
height: 1px;
width: 1px;
margin: -1px;
overflow: hidden;
padding: 0;
position: absolute;
}
A great practice is to create a "Skip to content" link to the anchor of the main body of content. Visually-impaired users probably don't want to listen to your full navigation tree on every single page. Make the link visually hidden. Users can just hit tab to access the link.
For more on accessibility and hidden content, see:
https://webaim.org/techniques/css/invisiblecontent/
https://webaim.org/techniques/skipnav/
Summarizing all the other answers:
visibility
display
element with visibility: hidden, is hidden for all practical purposes (mouse pointers, keyboard focus, screenreaders), but still occupies space in the rendered markup
element with display:none, is hidden for all practical purposes (mouse pointers, keyboard focus, screenreaders), and DOES NOT occupy space in the rendered markup
css transitions can be applied for visibility changes
css transitions can not be applied on display changes
you can make a parent visibility:hidden but a child with visibility: visible would still be shown
when parent is display:none, children can't override and make themselves visible
part of the DOM tree (so you can still target it with DOM queries)
part of the DOM tree (so you can still target it with DOM queries)
part of the render tree
NOT part of the render tree
any reflow / layout in the parent element or child elements, would possibly trigger a reflow in these elements as well, as they are part of the render tree.
any reflow / layout in the parent element, would not impact these elements, as these are not part of the render tree
toggling between visibility: hidden and visible, would possibly not trigger a reflow / layout. (According to this comment it does: What is the difference between visibility:hidden and display:none? and possibly according to this as well https://developers.google.com/speed/docs/insights/browser-reflow)
toggling between display:none to display: (something else), would lead to a layout /reflow as this element would now become part of the render tree
you can measure the element through DOM methods
you can not measure the element or its descendants using DOM methods
If you have a huge number of elements using visibility: none on the page, the browser might hang while rendering, as all these elements require layout, even though they are not shown
If you have a huge number of elements using display:none, they wouldn't impact the rendering as they are not part of the render tree
Resources:
https://developers.google.com/speed/docs/insights/browser-reflow
http://www.stubbornella.org/content/2009/03/27/reflows-repaints-css-performance-making-your-javascript-slow/
Performance differences between visibility:hidden and display:none
Other Info:
There are some browser support idiosyncrancies as well, but they seem to apply to very old browsers, and are available in the other answers, so I have not discussed them here.
There are some other alternatives to hide element, like opacity, or absolute positioning off screen. All of them have been touched upon in some or the other answers, and have some drawbacks.
According to this comment (Performance differences between visibility:hidden and display:none), if you have a lot of elements using display:none and you change to display: (something else), it will cause a single reflow, while if you have multiple visibility: hidden elements and you turn them visible, it will cause reflow for each element. (I don't really understand this)
One other difference is that visibility:hidden works in really, really old browsers, and display:none does not:
https://www.w3schools.com/cssref/pr_class_visibility.asp
https://www.w3schools.com/cssref/pr_class_display.asp
The difference goes beyond style and is reflected in how the elements behave when manipulated with JavaScript.
Effects and side effects of display: none:
the target element is taken out of the document flow (doesn't affect layout of other elements);
all descendants are affected (are not displayed either and cannot “snap out” of this inheritance);
measurements cannot be made for the target element nor for its descendants – they are not rendered at all, thus their clientWidth, clientHeight, offsetWidth, offsetHeight, scrollWidth, scrollHeight, getBoundingClientRect(), getComputedStyle(), all return 0s.
Effects and side-effects of visibility: hidden:
the target element is hidden from view, but is not taken out of the flow and affects layout, occupying its normal space;
innerText (but not innerHTML) of the target element and descendants returns empty string.
As described elsewhere in this stack, the two are not synonymous. visibility:hidden will leave space on the page whereas display:none will hide the element entirely. I think it's important to talk about how this affects the children of a given element. If you were to use visibility:hidden then you could show the children of that element with the right styling. But with display:none you hide the children regardless of whether you use display: block | flex | inline | grid | inline-block or not.
display:none; will neither display the element nor will it allot space for the element on the page whereas visibility:hidden; will not display the element on the page but will allot space on the page.
We can access the element in DOM in both cases.
To understand it in a better way please look at the following code:
display:none vs visibility:hidden

Resources