프론트엔드/CS

[CSS - Hover, Opacity] Hover시 디테일 표시

턴태 2022. 9. 25. 11:37

See the Pen Untitled by seongtae (@stae1102) on CodePen.

각 품목에 hover 했을 때, 이미지의 상세설명이 나오는 디자인을 구현해봅니다.

 

display: none으로 구현하는 것은 transition의 영향을 받지 않기에 opacity를 조정하여 구현하는 것이 보기 좋습니다.

 

1. HTML

<!DOCTYPE html>
<html lang="ko">

<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <link rel="stylesheet" href="css/style.css">
</head>

<body>

  <div class="items">
    <div class="item">
      <img src="images/product-01.png" alt="" style="width:100%">
      <div class="caption">
        <h2>MacBook Air M2 13in</h2>
        <p>
          Don’t take it lightly.
        </p>
        <p>Price : $1199</p>
        <a href="#none">View details</a>
      </div>
    </div>
    <div class="item">
      <img src="images/product-01.png" alt="" style="width: 100%">
      <div class="caption">
        <h2>MacBook Air M2 13in</h2>
        <p>
          Don’t take it lightly.
        </p>
        <p>Price : $1199</p>
        <a href="#none">View details</a>
      </div>
    </div>
    <div class="item">
      <img src="images/product-01.png" alt="" style="width: 100%">
      <div class="caption">
        <h2>MacBook Air M2 13in</h2>
        <p>
          Don’t take it lightly.
        </p>
        <p>Price : $1199</p>
        <a href="#none">View details</a>
      </div>
    </div>
  </div>

  <script src="script/jquery-1.12.4.js"></script>
  <script src="script/custom.js"></script>
</body>

</html>

이미지 파일은 구글에서 가져와 링크하면 됩니다. 이미지가 꽤 커서, width를 100%로 조정했습니다. CSS로 부모에 width를 지정하면 줄어듭니다.

 

2. CSS 작성

2-1. 상품 품목 표시

.items {
  text-align: center;
}
.item {
  display: inline-block;
  width: 300px;
  height: 300px;
  position: relative;
  margin: 10px;
}

.item img {
  position: absolute;
  top: 50%;
  left: 0;
  transform: translate(0, -50%);
}

각 품목이 가로로 배치될 수 있도록 inline-block으로 바꿉니다. 그리고 상세설명이 품목과 겹쳐서 보일 수 있도록 position을 relative로 정합니다.

 

img태그가 item의 중앙에 올 수 있도록 top은 50%로, 이미지 크기가 크기 때문에 translate로 -50% 위로 올라올 수 있게 했습니다.

 

2-2. 상세 설명 작성

.caption {
  width: inherit;
  height: inherit;
  background-color: rgba(0, 0, 0, 0.3);
  position: absolute;
  top: 0;
  left: 0;
  color: #fff;
  padding: 20px;
  box-sizing: border-box;
  opacity: 0;
  transition: 0.5s;
}

.caption a {
  color: #fff;
  background-color: #333;
  text-decoration: none;
  padding: 7px;
  border-radius: 3px;
}

item과 같은 크기가 될 수 있게 너비와 높이를 상속받습니다. 그리고 이미 안 보이게 하기 위해 opacity는 0으로 지정합니다. 그리고 padding을 사용하기 위해 box-sizing을 border-box로 지정했습니다.

 

2-3. Hover

.caption a:hover {
  background-color: #fff;
  color: #000;
}

.item:hover .caption {
  opacity: 1;
}

각각 호버 되면 보일 수 있게 opacity를 다시 1로 지정해 display 시켰습니다.