csssvgcss-selectorshovertransition

CSS3 Simple Transition with SVG: appearing and disappearing on mouse :hover


I am trying to make a simple css3 transition work with two items: an svg box (representing an svg drawn logo) and a <p> tag (representing a title name tag) behind it.

By default only the box should show and the text should be hidden. When the mouse hovers over the SVG box, the box should disappear with a simple CSS fade transition (or even better shadow blur for bonus points ;-) and then the name title should appear to focus (from shadowy blur) all in say 1 second.

At the moment I'm stuck since my code is broken to activate the mouse hover. What am I doing wrong at this stage? Isn't svg:hover p the correct selector for my last move? And how to set the transition fade effects?

*{margin: 0; padding: 0;}

svg{
position: absolute;
fill: rgba(0,200,0,1);
z-index: 2;
top: 0px;
left:0px;
display:block;
}

p{
position: absolute;
z-index: 1;
top:70px;
display: block;
color: rgba(0,0,200,0); /* hide the title as default */
}

svg:hover{
fill: none;
}
svg:hover p{
color: rgba(0,0,200,1); /* on mouse over svg, show title. // Doesn't work!! */
}
<svg width="100" height="100" viewBox="0 0 100 100">
  <rect x="10" y="10" width="100" height="100"/>
  <p>Title of this Website</p>
</svg>http://stackoverflow.com/questions/ask#


Solution

  • You can't place elements inside the SVG. You should place both SVG and paragraph inside a container, and set the hover effect to act on the container. For the transition, use the transition property on each element, or just place it on all child elements of the parent. Something like this:

    <style type="text/css">
        * {margin: 0; padding: 0;}
    
        .svg-container * {
            -webkit-transition: all 1000ms ease;
            -moz-transition: all 1000ms ease;
            -o-transition: all 1000ms ease;
            -ms-transition: all 1000ms ease;
            transition: all 1000ms ease;
        }
    
        svg {
            position: absolute;
            fill: rgba(0, 200, 0, 1);
            z-index: 2;
            top: 0;
            left: 0;
            display: block;
            opacity: 1;
        }
    
        p {
            position: absolute;
            z-index: 1;
            top:70px;
            display: block;
            color: rgba(0,0,200,0);
        }
    
        .svg-container:hover svg {
            opacity: 0;
        }
    
        .svg-container:hover p {
            color: rgba(0,0,200,1);
        }
    </style>
    
        <div class="svg-container">
            <svg width="100" height="100" viewBox="0 0 100 100">
              <rect x="10" y="10" width="100" height="100"/>
            </svg>
            <p>Title of this Website</p>
        </div>