CSS hover over on thumbnails in wordpress

2019-02-21 00:24发布

问题:

I am trying to create a grid of thumbnails in wordpress, which I've managed to do. Then when the user hovers over an image, I want it to go a semi transparent colour and show the post title underneath. I think I've begun to make some way with the code, but at present the hover over appears underneath the image instead of ontop of the thumbnail. I was wondering if somebody could help me with this? I think it is the CSS that is the problem. I tried position: absolute but that just sticks in one place to the top of the grid.

<div id="gridContainer">
<?php
$c = 1; //init counter
$bpr = 3; //boxes per row
if(have_posts()) :
    while(have_posts()) :
        the_post();
?>


<div class="post" id="post-<?php the_ID(); ?>">


<div class="postImage">
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_post_thumbnail('grid-post-image'); ?></a>
</div>

<div class="hover">
                <h1 class="title"><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h1>
            </div>
            </div>


<?php
if($c == $bpr) :
?>
<div class="clr"></div>
<?php
$c = 0;
endif;
?>
<?php
        $c++;
    endwhile;
endif;
?>
<div class="clr"></div>
</div>

And here is the CSS, which is what I think needs altering.

.post {
    float: left;
    width: 275px;
}

.clr {
    clear:both;
}


.hover {
      width: 275px;
   height: 185px;
    top: 0;
    z-index: 1;
        background: #fff;
      opacity:0;
}

.hover:hover{
      opacity:0.9;
}

回答1:

<style>
    .postImage{position:relative;}
    .postImage>a{position:absolute; top:0; left:0; z-index:0;}
    .postImage>h1{display:none; position:absolute; top:50%; left:0; z-index:1;}
    .postImage:hover img{opacity:0.5;}
    .postImage:hover h1{display:block;}
</style>

Put both elements (image and h1) in the same div

<div class="postImage">
    <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_post_thumbnail('grid-post-image'); ?></a>
    <h1 class="title"><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h1>
</div>