简体   繁体   中英

Use clip:rect on button in HTML

I am trying to load a image to a button using CSS.

I seem to be able to make the button size work etc. but I can't seem to get the image to show correctly.

My icons.png has 8 icons and I only want to display one of them on the button. I am trying to use clip:rect to select just one of them but it doesn't seem to be working.

It seems to be showing all the icons on the button where I thought using clip:rect would allow me to select just one of the icons in my image.

Does anyone know where I have gone wrong? (Note: I can't use jQuery for this)

Here is my CSS and HTML I am using..

<style type="text/css">
.button1
{
    position:absolute;
    left: 20px;
    width:100px; 
    height:100px;
    top:20px;
    clip:rect(0px,100px,100px,0px); /* rect(top, right, bottom, left) */ 
    cursor: pointer; /* hand-shaped cursor */ 
    cursor: hand; /* for IE 5.x */ 
}

</style>


<body bgcolor="#DFDFDF">

    <button class="button1"><img src="icons.png"/></button>

</body>

This is what it is doing..

在此处输入图片说明

Move the button image to the style. You've already defined the size of the button with width and height. If the button is larger than the "sprite" image (the intended button background) you'll see the next button image. Both position and button size needs to be correctly sized. From your example image, the button must be sized smaller, about 70 pixels or so.

    .button1
    {
        width:100px; 
        height:100px;   
        background-image: url(icons.png);
        background-position: -70px -10px; /* hor vert from top left*/

    }


    <button class="button1"></button>

I ended up adding a class to my image

<style type="text/css">
.button1
{
    position:absolute;
    left: 20px;
    width:100px; 
    height:100px;
    top:20px;
    cursor: pointer; /* hand-shaped cursor */ 
    cursor: hand; /* for IE 5.x */ 
}


  img.button_logo
    {
        position:absolute;
        left: 20px;
        top:20px;
        clip:rect(0px,100px,100px,0px); /* rect(top, right, bottom, left) */ 
        cursor: pointer; /* hand-shaped cursor */ 
        cursor: hand; /* for IE 5.x */ 
    }

</style>


<body bgcolor="#DFDFDF">

    <button class="button1"><img class="button_logo" src="icons.png"/></button>

</body>

Now it displays just like it was meant to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM