How to Move a CSS Image

Developers make images on Web page move by modifying the Cascading Style Sheet properties of their images. These CSS properties allow you to specify an image's location in relation to the top left corner of the monitor screen. HTML, the language used to create Web pages, has no methods you can use to reposition objects. You can, however use JavaScript and CSS to move an image to any location on your Web page.

Instructions

    • 1

      Open an HTML page using your HTML editor or Notepad.

    • 2

      Add an image to the page by inserting the code shown below into the page's body section.

      <img id = "button1" src="XYZ.gif" />

      Replace "XYZ.gif" with the image path to a real image on your hard drive. If you prefer to test using an image on the Web, replace "XYZ.gif" with the image's URL instead.

    • 3

      Add the following button code below the code shown in the previous step:

      <input type="button" value="Move Image" onclick="return moveImage('button1','100','200')" />

      This button allows you to test your code. When you click the button, it passes the image's id to a JavaScript function named "moveImage." It also passes 100 and 200. These are the x and y screen coordinates defining the location to which you wish to move the image. These values are in pixels.

    • 4

      Add the following JavaScript code below the CSS code described in the last step:

      function moveImage(imageID, xLocation, yLocation) {

      var imageObject = document.getElementById(imageID);

      imageObject.style.position = "absolute";

      imageObject.style.top = yLocation + "px";

      imageObject.style.left = xLocation + "px";

      }

      This function moves the image; it receives the id of the image to move along with the x and y screen coordinates described in the previous step.

    • 5

      Save the document and view it in your browser. Click the button to make the image move.

Tips & Warnings

  • Move other images by calling the "moveImage" function, and passing it the id of the image you wish to move. The function moves any object passed to it. Test your code before moving it onto your Web server. Do not let the x and y coordinates you pass the function move your image off the screen to where site visitors cannot see it. This may happen if you make the values of "xLocation" and "yLocation" too large.

Related Searches:

References

Resources

Comments

Related Ads

Featured