首页 > 解决方案 > CSS 过渡行为不正确

问题描述

我不确定为什么当鼠标悬停在图像上时图像正在翻译。另外,让我知道是否有什么可以移动或更改我的 HTML 或 CSS 的结构以使其更具功能性,因为我是 Web 开发的新手。

html {
  overflow: hidden;
}

body {
  background-image: url("https://images.unsplash.com/photo-1617538781871-bfe89e84b61f?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=976&q=80");
  background-attachment: fixed;
  background-position: center; 
  background-repeat: no-repeat;
  background-size: cover;
  height: 100vh;
  margin: 0;
  backdrop-filter: blur(32px);
}

.image {  
  min-height: 500px;
  border-style: solid;
  border-width: 50px;
  margin: auto;
  display: block;
  margin: 0;
  position: absolute;
  top: 50%;
  left: 50%;
  height: 50vh;
  
  box-shadow: 0px 0px 20px #000000;
  transition: all 0.5s;
  transform: translate(-50%, -50%);
}

.image:hover {
  transform: scale(1.05);
  box-shadow: 0px 0px 50px #000000;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="/style.css">
    <script src="/script.js" defer></script>
  </head>  
  <body>
    <img class="image" src="https://images.unsplash.com/photo-1617538781871-bfe89e84b61f?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=976&q=80" alt="Image">
  </body>
</html>

标签: css

解决方案


这是因为transform: translate(-50%, -50%);图像的原因。在图像悬停时,您将覆盖该transform属性。

您可能希望实现另一种使图像居中的方式,例如将其包装在容器或其他东西上并使用 flexbox。这是一个例子:

html {
  overflow: hidden;
}

body {
  background-image: url("https://images.unsplash.com/photo-1617538781871-bfe89e84b61f?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=976&q=80");
  background-attachment: fixed;
  background-position: center; 
  background-repeat: no-repeat;
  background-size: cover;
  height: 100vh;
  margin: 0;
  backdrop-filter: blur(32px);
}

.container {
/* Make this change */
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.image {  
  min-height: 500px;
  border-style: solid;
  border-width: 50px;
  margin: auto;
  display: block;
  margin: 0;
  height: 50vh;

  box-shadow: 0px 0px 20px #000000;
  transition: all 0.5s;
}

.image:hover {
  transform: scale(1.05);
  box-shadow: 0px 0px 50px #000000;
}
<div class="container">
<img class="image" src="https://images.unsplash.com/photo-1617538781871-bfe89e84b61f?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=976&q=80" alt="Image">
</div>


推荐阅读