当鼠标悬停在图像上方时,使文本位于图像的中间

时间:2019-05-30 22:04:06

标签: html css

当鼠标悬停在网页上时,我想在网页上的所有图像上添加标题(粗体)和子标题(非粗体)。我已经具有悬停时图像淡入/更改颜色的效果。以下是图像:https://imgur.com/a/xLXSUkx

这是它的HTML代码:

<div class="JA-linkWrap JA-Notprojects JA-NotObjects floatleft" style="width:300px;">

        <a href="https://canadacouncil.ca/initiatives/venice-biennale" 
        class="JA-projectPageLink">

          <img src="images/GRID/111%20jpeg%20grid.jpg" alt="" class="JA- 
newsmediaImage">
         <h2 class = "img_head"> The Octa. </h2>
         <p class = "img_description"> Arch. </p>

            </a>  

    </div>   

这是.JA-linkWrap的CSS:

.JA-linkWrap {
   float: left;
   margin: 12px;
}

更多CSS:

* {
    margin: 0;
    padding: 0;
    border: 0;
}


.JA-linkWrap img:hover {
    -webkit-filter: brightness(90%);
}


.img_head{
  position: absolute;
  color: #000;
  visibility: hidden;
  opacity: 0;
  transition: opacity.2s, visibility .2s;

}

.img_description{
  position:inherit;

  color:#000;
  visibility: hidden;
  opacity: 0;
  transition: opacity.2s, visibility .2s;
}

.JA-linkWrap:hover .img_description{
  visibility: visible;
  opacity: 1;
}



.JA-linkWrap:hover .img_head{
   visibility: visible;
  opacity: 1;
}

当我将鼠标悬停在图像上时,这是我尝试的结果:https://imgur.com/a/Fkuf0eE 如您所见,图像的标题和说明都在图像下方。我希望它们位于图像的中心。 。请具体说明,我对此并不陌生。

1 个答案:

答案 0 :(得分:0)

您应该在标题元素上添加一个包装器,然后像图像的框一样设置包装器的大小。然后使用flexbox在包装器内垂直对齐标题。另外,删除宽度为300px的内联样式

.JA-linkWrap {
   float: left;
   margin: 12px;
  position: relative;
}

* {
    margin: 0;
    padding: 0;
    border: 0;
}


.JA-linkWrap:hover img {
    -webkit-filter: brightness(90%);
}


.img_head{
  color: #000;
  visibility: hidden;
  opacity: 0;
  transition: opacity.2s, visibility .2s;
}

.img_description{
  color:#000;
  visibility: hidden;
  opacity: 0;
  transition: opacity.2s, visibility .2s;
}

.JA-linkWrap:hover .img_description, .JA-linkWrap:hover .img_head {
  visibility: visible;
  opacity: 1;
}

.title-wrapper {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  flex-direction: column; 
  justify-content: center;
  flex-wrap: wrap;
}

.title-wrapper .img_head, .title-wrapper .img_description {
    background-color: white;
}
<div class="JA-linkWrap JA-Notprojects JA-NotObjects floatleft">

        <a href="https://canadacouncil.ca/initiatives/venice-biennale" 
        class="JA-projectPageLink">

          <img src="https://picsum.photos/id/237/500/300" alt="" class="JA- 
newsmediaImage">
          
          <div class="title-wrapper">
         <h2 class = "img_head"> The Octa. </h2>
         <p class = "img_description"> Arch. </p>
          </div>

            </a>  

    </div>