Setting the Position Type
The position property sets how an element is positioned. The allowed values are:
Value | Description |
---|---|
static | The element is laid out as normal (default value). |
relative | The element is positioned relative to its normal position. |
absolute | The element is positioned relative to its first ancestor that is static positioned. |
fixed | The element is laid out relative to the browser window. |
You use the top, bottom, left, and right properties to offset the element.
<!DOCTYPE HTML>
<html>
<head>
<title>Example</title>
<style>
img {
top: 5px;
left:150px;
border: medium double black;
}
</style>
</head>
<body>
<p>
HyperText Markup Language (HTML) is the main markup language for
displaying web pages and other information that can be displayed
in a web browser(From From Wikipedia, the free encyclopedia).
</p>
<p>
HyperText Markup Language (HTML) is the main markup language for
displaying web pages and other information that can be displayed
in a web browser(From From Wikipedia, the free encyclopedia).
</p>
<img id="myImage" src="http://java2s.com/Book/HTML-CSSImages/star.png" alt="small"/>
<p>
HyperText Markup Language (HTML) is the main markup language for
displaying web pages and other information that can be displayed
in a web browser(From From Wikipedia, the free encyclopedia).
</p>
<p>
<button>Static</button>
<button>Relative</button>
<button>Absolute</button>
<button>Fixed</button>
</p>
<script>
var buttons = document.getElementsByTagName("BUTTON");
for (var i = 0; i < buttons.length; i++) {
buttons[i].onclick = function(e) {
document.getElementById("myImage").style.position =
e.target.innerHTML;
};
}
</script>
</body>
</html>
The top, bottom, left, and right properties have the relative value to position the element.
We can use the fixed value to make the element stay at the same location during the rest of the content scrolling up or down.
Click to view the demo