设置父母的身高取决于孩子的数量?

时间:2016-01-12 17:29:03

标签: css

是否可以在CSS中设置父级高度,具体取决于元素的子级数量?

像:

.parent:has-1-children {
    height: 60px;
}
.parent:has-2-children {
    height: 110px;
}
.parent:has-3-children {
    height: 160px;
}

或者简单地说:

.parent {
    height: calc(this.children() * 50px + 10px);
}

1 个答案:

答案 0 :(得分:0)

JavaScript解决方案(使用CSS转换)

http://jsfiddle.net/urq1j3aj/



var menu = document.getElementById("menu")
var menuUl = document.getElementById("list")

menu.onmouseover = function() {
  menuUl.style.height = menuUl.scrollHeight + "px"
  menu.classList.add("hover")
}
menu.onmouseout = function() {
  menuUl.style.height = "0"
  menu.classList.remove("hover")
}

#menu #list {
  height: 0;
  transition: height 0.15s ease-out;
  overflow: hidden;
  background: #d5d5d5;
}
#menu.hover #list {
  transition: height 0.25s ease-in;
}

<div id="menu">
  <a>hover me</a>
  <ul id="list">
    <!-- Create a bunch, or not a bunch, of li's to see the timing. -->
    <li>item</li>
    <li>item</li>
    <li>item</li>
    <li>item</li>
    <li>item</li>
  </ul>
</div>
&#13;
&#13;
&#13;

简化的内联JavaScript版本:

&#13;
&#13;
#menu #list {
  height: 0;
  transition: height 0.15s ease-out;
  overflow: hidden;
  background: #d5d5d5;
}
&#13;
<div onmouseover="this.querySelector('ul').style.height = this.querySelector('ul').scrollHeight + 'px'" 
     onmouseout="this.querySelector('ul').style.height='0'">
  <a>hover me</a>
  <ul>
    <li>item</li>
    <li>item</li>
    <li>item</li>
    <li>item</li>
    <li>item</li>
  </ul>
</div>
&#13;
&#13;
&#13;