How can we fix an element in HTML page without using <!doctype>
? Thanks in advance
views:
47answers:
2Using absolute positioning (e.g., position: absolute
or position: fixed
) in the style (examples):
Absolute (scrolls with page):
<style type='text/css'>
#foo {
position: absolute;
left: 10px;
top: 10px;
}
</style>
<div id='foo'>This is foo at 10x10</div>
Or if you prefer it inline:
<div style='position: absolute; left: 10px; top: 10px;'>This is foo at 10x10</div>
Fixed (doesn't scroll):
<style type='text/css'>
#foo {
position: fixed;
right: 10em;
top: 2em;
}
</style>
<div id='foo'>This is foo at 10x10</div>
Or if you prefer it inline:
<div style='position: fixed; right: 10em; top: 2em;'>This is foo in the upper right</div>
Or if you want to do it via JavaScript (since your question was originallly tagged javascript
):
var div = document.getElementById('foo');
div.style.position = "absolute"; // or "fixed" or whatever
div.style.left = "10px";
div.style.top = "10px";
Off-topic, but I would always recommend using a DOCTYPE. Without one, you run into different quirks in nearly every browser. While you still get browser differences with a DOCTYPE, they're fewer and a bit less insane...
The key to an absolute or fixed position element is that it's parent element (let's say a container div) has to have position:relative;
For instance, if you have a container div that is 960px wide and centered on the page (like below):
<div class="container">
<div id="AbsolutePositionedBox">
// Box Content Goes Here
</div>
</div>
the CSS to make it work correctly would be:
.container{
width:960px;
position: relative;
margin: 0 auto;
}
#AbsolutePositionedBox{
position: // absolute or fixed;
top: // pixels from the RELATIVE parent (makes it easier to manage);
LEFT OR RIGHT: // pixels from the RELATIVE parent;
}
Just like TJ mentioned above, a fixed positioning stays put, even when the user scrolls, where as an absolute position is just positioned relative to an element and will scroll with the rest of the content.
Again, I would also always recommend using a doctype.