Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to position an HTML element on top of another element without affecting the layout of the element(s) beneath?

Tags:

html

css

layout

Generally speaking, HTML layout is flow-based. Each element gets positioned after the one before it, either to the right of it or beneath it. There are plenty of exceptions, of course, that you can get by playing with styles, but even then, if you change the order of something, most things "flow" around it and make room for it.

But occasionally I see things that behave very differently, such as pages coming up with "dialog boxes" that float in the middle of the screen, that aren't constrained by the dimensions of the div they're parented by and don't displace other layout elements around them.

I'm trying to figure out a way to do something similar, but not quite the same. I've got a table that I'm using to display a grid (yes, actually using tables correctly) and I'd like to place an image on top of one of the grid cells. I can't put it in the cell, because it's larger than the cell and I don't want to stretch my grid out, but I want it to always display at the same position relative to the grid, even if the browser window scrolls or is resized.

I figure there has to be some way that I can do this. If I put an ID or Class on one of the <TD> cells, how do I create an <Image> that is not part of the <TD> or even the <TABLE> that it belongs to, but will always position itself over the top of that <TD> cell without displacing anything or affecting its layout?

like image 555
Mason Wheeler Avatar asked Nov 03 '22 04:11

Mason Wheeler


2 Answers

To expand on both CJGreen and Napolux's suggestions, you can still place the image in the table cell, but position it absolutely.

[Edit] Since defining the position of table cells is supposedly illegal (therefore ignored by Firefox), you can wrap the content of each <td> in a <div> element (preferably with JS so you don't have to make massive changes) and then set the <div> position to relative:

CSS:

table td > div {
    position: relative;
}
table td > div img {
    position: absolute;   
    z-index: 999;
}

JS:

$(document).ready(function() {
   $("td").wrapInner('<div />'); 
});

See the (updated) fiddle here - http://jsfiddle.net/teddyrised/qyu3g/

like image 58
Terry Avatar answered Nov 09 '22 09:11

Terry


If you use

table {position:relative;}

then you can use:

table img {
    position:absolute;
    top: #px;
    left: #px;
}

This will offset the image to a particular location within the containing table and take it out of the flow of the rest of the table around it.

like image 41
Caspar Avatar answered Nov 09 '22 10:11

Caspar