首页 > 解决方案 > CSS OnHover - 改变另一个元素的属性以及它本身

问题描述

我正在处理侧边栏菜单并希望它部分折叠,这意味着我必须在悬停时显示文本并在不悬停时隐藏文本。我知道另一个问题是关于在悬停时更改另一个元素的属性,但我在更改自身和另一个属性时遇到了麻烦。

一般 HTML 布局:

.sidebar {
  position: fixed;
  top: 0;
  left: 0;
  background-color: #1d326b; 
  height: 100%;
  width: 60px;
  transition: 0.3s;
  border-radius: 0 5px 5px 0;
  font-family: 'Open Sans', sans-serif;
  overflow: hidden;
}

.sidebar:hover > .text {
    display: block; /*Supposed to display text*/
  width: 150px; /*Expands the sidebar*/
}
<div class="sidebar">
   <!--more containers...-->
   <!--text below is deeply nested-->
   <p class="text">Displayed Text</p>
</div>

这个问题有纯css解决方案吗?任何帮助,将不胜感激!

标签: htmlcss

解决方案


我认为您要实现的是宽度动画,如果您想要> .text从悬停选择器中删除它:

.sidebar {
  position: fixed;
  top: 0;
  left: 0;
  background-color: #1d326b; 
  height: 100%;
  width: 60px;
  transition: 0.3s;
  border-radius: 0 5px 5px 0;
  font-family: 'Open Sans', sans-serif;
  overflow: hidden;
  color: #FFF; 
}

.sidebar:hover {
  display: block; /*Supposed to display text*/
  width: 150px; /*Expands the sidebar*/
}

.text {
  width: 150px;
  display: none;
}

.sidebar:hover .text {
 display: block;
}
<div class="sidebar">
   <!--more containers...-->
   <!--text below is deeply nested-->
   <p class="text">Displayed Text</p>
</div>


推荐阅读