开发者

CSS cover existing element

I'm u开发者_StackOverflowsing jQuery to create an element that exactly overlays any existing one. That's the intention, at least.

The context is similar to what goes on here:

A List Apart: Making Compact Forms More Accessible

The idea is that you have an element, such as an <input>, and under certain conditions you display another element (in this case a <label>) absolutely positioned on top of it as a hint. Though the general principle is useful in other scenarios as well.

There are several existing libraries that do this sort of thing, but they all seem to break down along the same lines.

The naive approach:

  • Create the cover element with display:block and position:absolute.
  • Set the left and top of your cover element to match your covered element

Problem: The cover's position no longer matches whenever the page layout changes, such as hiding a paragraph or resizing the display.

A slightly improved approach:

  • Create the cover element with display:block and position:absolute
  • Add the cover element immediately before the covered element in the DOM
  • Set the bottom and right margin of the cover to the negative height and width of the cover

This approach solves the problem with fluid layouts, but it adds a problem such that if the covered element is within an inline block, the cover will create a linebreak when it shows up (because of insertion of a block element).

Presumably this is a problem that has been solved already somewhere by someone.


The 'naive' approach is the best but you missed a bit.

<div><i>Element to be covered</i> <span>Shiny new element</span></div>

It's doesn't have to be divs, is and spans but this is just for visualisation, it's the nesting that's important - I only used i in that code to show you could "span" the original text for styling too..

div {position: relative; width: 200px; height: 50px;}
span {position: absolute; top: 0; left: 0; height: 100%; width: 100%;}

that is virtually the same as approach #1, except with the important addition of position: relative; to the outer container (the original element) - with this added the "new" element (span) will always appear in relation to it, which solves:

Problem: The cover's position no longer matches whenever the page layout changes, such as hiding a paragraph or resizing the display.*

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜