Search code examples
htmlcssclip

css clip is not working


I tried several different permutations on css position for parent and child. I have a spritesheet with 3 cells. I have some old code that uses the background image trick and I'm trying to update it to use clip :rect( ) inside css. Ideally I'll have a span that controls the display size. and combination of css properties on the image will get the right cell. What am I missing here?

<html>
    <head>
        <style>
        .marketItemImage{
            display: inline-block;
            width: 100px;
            height: 104px;
            border: 3px solid black;
            overflow: hidden;
        }
        img {
            clip: rect("0px 300px 104px 200px");
        }
        </style>
    </head>
    <body>
        <span class="marketItemImage">
            <img src="http://villagegamedev2.appspot.com/client/assets/textures/sprites/plantsSmall.png" />
        </span>
    </body>
</html>

Solution

  • Well, you may want to change the clip value to rect(top, right, bottom, left), then change the position of your image to absolute so you'll be able to freely adjust its position (left/top). You'll then need to calculate the top/left accordingly based on the size of the span block and the size of your sprite.

    Here is an example.

    Some basic information on clip property can be found here http://www.w3schools.com/cssref/pr_pos_clip.asp

    .marketItemImage {
      display: inline-block;
      width: 100px;
      height: 104px;
      border: 3px solid black;
      overflow: hidden;
    }
    img {
      position: absolute;
      left: -189px;
      clip: rect(0px, 300px, 104px, 200px);
    }
     <span class="marketItemImage">
                <img src="http://villagegamedev2.appspot.com/client/assets/textures/sprites/plantsSmall.png" />
            </span>