HTML and CSS Reference
In-Depth Information
Changing the location of an element
By using the methods to retrieve an element from the DOM in JavaScript, you can apply styles
dynamically through code that can change the element's position on the page. How elements
are laid out on the page can affect how elements behave when they are repositioned.
A few options determine how HTML elements are positioned on a webpage. By default,
all HTML elements flow statically from left to right in the same order that they are declared
in the HTML page. However, CSS provides a mechanism to specify some advanced options in
element position. You can position elements by using absolute positioning or relative position-
ing . With absolute positioning, the element is placed in the exact location specified, relative to
its container's borders. However, with relative positioning, the element is positioned relative
to its immediate left sibling's coordinates. You can apply four properties individually or in
combination to control the position of an element: Top , Left , Right , and Bottom . Each property
takes a distance parameter that specifies the relative distance of the object from a reference
point based on the positioning attribute specified. When using absolute or relative position-
ing, the default border or margin settings are ignored because the object is positioned where
the positioning attributes direct the element to be.
The code in Listing 1-3 demonstrates this.
LISTING 1-3 HTML and JavaScript to illustrate positioning
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8"/>
<title></title>
<style>
html, body {
height: 100%;
width: 100%;
}
img {
height: 150px;
width: 225px;
}
</style>
<script>
window.onload = function () {
var top = document.getElementById("topText");
var left = document.getElementById("leftText");
var pos = document.getElementById("positioning");
document.getElementById("btnPosition").onclick = function () {
var img = document.getElementById("orange2");
img.style.position = pos.value;
img.style.left = left.value + "px";
img.style.top = top.value + "px";
}
}
</script>
</head>
 
 
Search WWH ::




Custom Search