Search code examples
csscss-shapes

Restrict a click to a specific shape


I have this image/polygon defined in css like this:

.post-wrapper {
    position: relative;
    width: 250px;
    height: 420px;
    float: left;
    background-color: #ddc;
    -webkit-clip-path: polygon(50% 100%, 100% 50%, 50% 0, 0 50%);
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover; 
}

you can see the image:

Maintain click event in CSS shape

It defines a sort of rectangle, this is a clickable image that redirects to another page, and people are able to click in any part of the rectangle but I only want them to click on the polygon. Anyone knows how can I do this here in my code?

Fidde


Solution

  • CSS solution

    You may maintain the boundaries of the diamond shape and make only the part with the image clickable by using css transform properties. The point is to use the skew property so that the link actualy has a diamond shape and therefore isn't clickable outside this shape (see following demo and screenshot). Then, you need to "counter transform" the content so it isn't skewed.

    DEMO

    screenshot :

    diamond shape with proper boundaries

    Relevant CSS :

    a{
        width: 216px;
        height: 250px;
        overflow:hidden;
        display:inline-block;
        background:red;
    
        -webkit-backface-visibility:hidden; /* to reduce pixelisation on borders in chrome */
    
        -webkit-transform-origin:0 0;
        -ms-transform-origin:0 0;
        transform-origin:0 0;
    
    
        -webkit-transform: translate(55%,0) rotate(30deg) skewY(30deg);
        -ms-transform: translate(55%,0) rotate(30deg) skewY(30deg);
        transform: translate(55%,0) rotate(30deg) skewY(30deg);
    }
    
    .post-wrapper {
        width: 250px;
        height: 432px;
        background: url(http://lorempixel.com/output/people-h-c-250-432-8.jpg) center center;
        background-size: cover; 
    
        -webkit-transform-origin:0 0;
        -ms-transform-origin:0 0;
        transform-origin:0 0;
    
        -webkit-transform:   skewY(-30deg) rotate(-30deg) translate(-50%,0);
        -ms-transform:   skewY(-30deg) rotate(-30deg) translate(-50%,0);
        transform:   skewY(-30deg) rotate(-30deg) translate(-50%,0);
    }