Search code examples
htmlcssperspective

How to use css perspective to match a div to visually fit inside a svg laptop screen?


I'm sure the question is confusing already. Essentially, I want to use css to absolutely position a div with perspective to look like it is inside of the laptop screen that I created with svg.

I believe it is possible using some combination of perspective, rotateX(), rotateY() but can't seem to get it right.

See this Codepen

Here's the relevant css:

.container {
    perspective: 500px;
}
.screenContents {
    transform: rotateX(10deg) rotateY(-10deg);
    /* 16:9 ratio to calculate size */
    --scale: 36;
    width: calc(16px * var(--scale));
    height: calc(9px * var(--scale));
    position: absolute;
    top: 30px;
    left: 300px;
}

Html:

<div class='container'>
    <div class='screenContents'>Screen Contents</div>
</div>
<img src='device.svg' />

Some other things I've tried are setting perspective-origin and/or using rotateZ()

SVG Dimensions and Info

In case it proves useful, here are some dimensions of the screen which I calculated from the svg:

area: 1529 sq pixels

(width and height calculated from each corner point)

width: ~500px
height: ~350px

The coordinates of each point of the svg screen which I used to find the height, width, and area:

top left: 382,514
top right: 882,503
bottom left: 312,187
bottom right: 816,151

Also, the svg is just a traced picture of a Google Pixel Go laptop which has a 13.3" screen size and 16:9 ratio

I feel like these dimensions must be included somehow in the final calculations.

Summary

I would like to position a div so that it looks like it is being viewed in the laptop screen. I don't know how to correctly do this and could use some pointers or a mad genius to create a solution for me. Use the codepen to mess around with it.

So, any css gurus out there that might be able to help????


Solution

  • Change below CSS

    .container {
    /*   perspective: 500px; */
    }
    
    .screenContents {
     transform: perspective(3651px) rotateY(-30deg) rotateX(18deg) rotate(3deg);
     --scale: 37;
     width: calc(16px * var(--scale));
     height: calc(10px * var(--scale));
    }