Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
495 views
in Technique[技术] by (71.8m points)

html - CSS :hover effect not working when I set an ID to the paragraph

I have the following css3 transition with ease effect:

HTML

<div class="button">     
    <a href="#" onMouseOver="clicksound.playclip()"></a>
    <p id="myId" class="top"></p>            
</div>

CSS

 * {
     padding: 0;
     margin: 0;
 }
 .button {
     width: 180px;
     margin-top: 45px;
 }
 .button a {
     display: block;
     height: 40px;
     width: 180px;
     /*TYPE*/
     color: black;
     font: 17px/50px Helvetica, Verdana, sans-serif;
     text-decoration: none;
     text-align: center;
     text-transform: uppercase;
 }
 .button a {
     background:url(http://imageshack.com/a/img819/761/dqj.gif);
     margin: -50 0 0 0;
     z-index: -1;
 }
  p#myId {
     background: url(http://imageshack.com/a/img854/1921/9ft3.png);
     display: block;
     height: 40px;
     width: 167px;
     margin: -40px 0 0 5px;
     z-index:-1;
     /*TYPE*/
     text-align: center;
     font: 12px/45px Helvetica, Verdana, sans-serif;
     color: #fff;
     /*POSITION*/
     position: absolute;
     /*TRANSITION*/
     -webkit-transition: margin 0.1s ease;
     -moz-transition: margin 0.1s ease;
     -o-transition: margin 0.1s ease;
     -ms-transition: margin 0.1s ease;
     transition: margin 0.1s ease;
 }
 .button:hover .top {
     margin: -67px 0 0 5px;
     line-height: 35px;
 }
 /*ACTIVE*/
 .button:active .top {
     margin: -70px 0 0 5px;
 }

If I change the p#myId selector to p in CSS, it works (the button goes up on hover), otherwise it won't.

Running demo on jsFiddle

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is that the selector handling your :hover behavior has a lower Specificity than the rule for the default behavior (p#id selector).

Changing this

.button:hover .top {

to this

.button:hover #myId.top {

will solve the problem: Running example

You can also apply an id to a parent object (lets' say <div id="container">), and then use

#container .button:hover .top {

A must-read: Specifics on CSS Specificity

Examples:

enter image description here

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...