问题描述:

Note: There seems to be a same problem before but I hope to ask it in better way, get an answer to mark as solved.

In short, transparent element borders are not really transparent because they take the color of the element background instead of being invisible eventhough it is drawn as an "outside border". How can I draw real transparent border with CSS?

Why do I want this?

Because I have a CSS menu with drop down on hover. Between the main menu and the sub menu, there is a requirement for a gap in between. The gap causes the hover to lose focus, thereby closing the menu. There may be other ways to do it, but transparent border, if possible, will be as neat.

HTML

<ul id="root">

<li>Item 1

<ul><li>Subitem 1</li></ul>

</li>

<li>Item 2

<ul><li>Subitem 2</li></ul>

</li>

</ul>

CSS

ul, li {

list-style: none;

margin: 0; padding: 0;

color: #fff;

}

ul ul { background-color: red; }

ul#root > li {

background-color: blue;

display: inline-block;

position: relative

}

ul#root > li > ul {

position: absolute;

display: none;

/* margin-top: 10px; want to have gap but the hover will lose focus*/

border-top: 10px solid green; /* if only this is transparent */

}

ul#root > li:hover > ul {

position: absolute;

display: block;

}

网友答案:

Use background color for li instead of ul & use padding top

ul#root > li > ul { padding-top:10px; background: transparent; }
ul#root > li > ul > li { background: #f00; }

or Use

ul#root > li > ul { border-top :10px solid rgba(0,0,0,0); }

or

ul#root > li > ul { border-top :10px solid transparent; }
网友答案:

enter code herehttp://jsfiddle.net/gkbcj9sr/2/

use rgba colour, but check if all browsers support them or not.

网友答案:

Check this fiddle: http://jsfiddle.net/gkbcj9sr/6/

I changed a little your css in order to keep your html intact:

Changed the ul ul rule, to ul ul li in order to add the background to li and not to the entire ul which was causing you troubles.

Added border-top: transparent to your ul#root > li > ul rule, to have your transparent gap.

Here's the new css:

ul, li {
    list-style: none;
    margin: 0; padding: 0;
    color: #fff;
}
#root { border: 1px solid green; }
ul ul li { background-color: red; } /* Background only in your li elemnts
ul#root > li {
    background-color: blue;
    display: inline-block;
    position: relative
}
ul#root > li > ul {
    position: absolute;
    display: none;
    /* margin-top: 10px; want to have gap but the hover will trigger */
    border-top: 10px solid transparent; /* transparent border top */
}
ul#root > li:hover > ul {
    position: absolute;
    display: block;
}

Hope this was you were looking for.

相关阅读:
Top