Pregunta

CSS:

.layers {
    position: relative;
    height: 500px;
    width: 500px;
    /* Some -webkit and -moz transformations */
}
.layers > div {
    position: absolute;
    height: 500px;
    width: 500px;
 }
.item {
    position: absolute;
    width: 5px;
    height: 5px; 
}

HTML:

<article class="someclass">
    <section class="layers">
       <div style="/* -webkit and -moz transformations */">
           <img src='image.png'>
           <div class="item" style="/* -webkit and -moz transformations */">test</div>
       </div>
    </section>
</article>

When loading this page, I get image.png with test on top of it 90% of the time.

(exact position depends on the transformations) The other 10% of the times I try loading the page, the item div is loaded as if the position is static which causes it not to be on top the the image.

My best guess is that it has something to do with what what gets loaded first, so there might not be an exact answer, but maybe there is something else I'm forgetting here.

Note: I tried this on Chrome and Safari, both the same results.

¿Fue útil?

Solución

The inconsistent behaviour is due to two things: one, you've not set the actual position (e.g. top/left) for the .items, and two, your image has no dimensions specified, so its size won't be known by the browser until it's loaded.

Because you haven't specified a position, but have specified absolute positioning, the .item elements are defaulting to the values they would have if they were statically positioned. That is, they'll be directly below the image.

I believe that when you're seeing the .items below the image, that's because the image is in your cache, so the browser knows how big it is on its initial layout run, and sets the static position of the .items below the image.

When you're seeing the .items on top of the image, that's because the browser hasn't worked out how big the image is on its initial layout run (i.e. it's still loading) so it positions the .items as though the image has zero height. Usually, once the image was loaded, the layout would be recalculated, and the .items would move down, but because you've specified their positioning as absolute, I believe the browser is assuming it doesn't need to reposition them, as the image size shouldn't affect their positioning, because they've been taken out of the normal layout flow.

Anyway. Specify an actual position for your absolutely-positioned elements, and everything should start working.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top