Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/84.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Html CSS:更改悬停时div的位置_Html_Css - Fatal编程技术网

Html CSS:更改悬停时div的位置

Html CSS:更改悬停时div的位置,html,css,Html,Css,在下面的HTML中,.layer的初始位置设置为顶部:-100%,我想将其悬停在.imagediv上进行更改。我正在尝试下面的代码,但悬停时它似乎没有任何作用 HTML: <div class="box"> <div class="image"> <a href="#"><img src="http://farm9.staticflickr.com/8356/8332233161_18e3a75de0_m.jpg" ><

在下面的HTML中,
.layer
的初始位置设置为
顶部:-100%
,我想将其悬停在
.image
div上进行更改。我正在尝试下面的代码,但悬停时它似乎没有任何作用

HTML:

<div class="box">
    <div class="image">
        <a href="#"><img src="http://farm9.staticflickr.com/8356/8332233161_18e3a75de0_m.jpg" ></a>
    </div>
    <div class="layer">Hide it first, show on hover over image</div>
     <div class="other">other</div>
</div>
.box{
    border: 1px solid red;
    width: 240px;
}

.box .image{
    position: relative;
    overflow: hidden;    
}

.box .layer{
    width: 240px;
    height: 146px;
    background: green;
    position: absolute;
    top: -100%;
}

.box .image:hover .layer{
    top: 0  
}
JSFiddle:

问题在于您使用的选择器,元素之间的空格表示第二个元素是前者的后代,而在本例中,元素是相邻的兄弟元素,这是使用
+
组合符描述的关系;因此:

.image:hover + .layer,
.layer:hover {
    top: 0  
}

我还定义了应用于
.layer:hover
的规则的原因是为了避免在将
.layer
放置在光标下时出现这种情况,从而停止
.layer:hover
选择器的应用(正如
.layer
实际上是“在途中”)

参考资料:


悬停状态的样式规则适用于
.box.image:hover.layer
。这意味着它将应用于嵌套在class
image
元素中的class
元素。但是,在当前代码中,
元素未嵌套在
图像
元素中

要解决此问题,只需将
元素移动到
图像
元素中,如下所示:

<div class="box">
<div class="image">
    <a href="#"><img src="http://farm9.staticflickr.com/8356/8332233161_18e3a75de0_m.jpg" ></a>
    <div class="layer">Hide it first, show on hover over image</div>
</div>
<div class="other">other</div>

先隐藏,然后在图像上方悬停显示
另外


在此处进行实际测试:

感谢您提供的详细答案。我刚刚在你的例子中添加了边距,但它不能正常工作。即使.image位置是相对的,.layer似乎并不关心: