我有一个静态元素
<img src="whatever.jpg" />
当我将悬停时,我希望将其缩放为全屏,绝对定位。仅仅使用css就可以做到这一点吗?
你可以使用position: absolute
并在悬停时将宽度和高度更改为100 vw/vh
,但要获得过渡,你需要首先声明img的宽度和高度。
body {
margin: 0;
padding: 0;
}
img {
transition: all 0.3s linear;
width: 200px;
height: 150px;
position: absolute;
}
img:hover {
width: 100vw;
height: 100vh;
}
<img src="http://placehold.it/350x150">
我可能使用了太多的CSS属性,但这仅仅是为了解释发生了什么。
// Normal status - without hover
img {
// Set the position relative to it's parent (body in this case)
position: relative;
// Automatically calculate distance between the top, left, right and bottom of the window
top: auto;
left: auto;
right: auto;
bottom: auto;
// Static width/height
width: 250px;
height: 250px;
}
// Hovered status
img:hover {
// Force the image in an fixed position (not respecting other elements)
position: fixed;
// Make sure it aligns to all sides
top: 0;
bottom: 0;
left: 0;
right: 0;
// Force it to have the height and width of the viewport (100%)
width: 100vw;
height: 100vh;
}