CSS FlexBox - 伸展孩子而不是父母?

时间:2017-08-31 19:27:21

标签: html css css3 flexbox

我有一个DIV,它有一个在悬停时显示的子div。

因为我正在使用" visibility:hidden"显示隐藏的div时,div不会拉伸,也不会显示父级。

我想要实现的目标:

  1. 父div不应该伸展。
  2. 子div(包含隐藏的div)应该伸展。
  3. 是否可以使用CSS而不定义静态宽度?

    CodePen:https://codepen.io/anon/pen/QMzXzx

    <style>
    
    .page{
    flex-direction:column;
    display:flex;
    align-items:center;
    }
    
    .parent{
    margin-top:4px;
    padding:5px;
    flex-direction:column;
    display:flex;
    align-items:center;
    border:2px solid black;
    }
    
    .child{
    margin-top:4px;
    border:1px solid black;
    flex-direction:column;
    display:flex;
    }
    
    .child-sub{
    visibility:hidden;
    }
    
    .child:hover .child-sub{
    visibility:visible;
    }
    </style>
    
    
    <div class="page">
    I want the parent div to NOT resize on child hover but the child div should resize. Can this be done with CSS?
        <div class="parent">Parent-div
            <div class="child">Child-div (Hover to display hidden div)
                <div class="child-sub">Sub-menu</div>
            </div>
        </div>
    </div>
    

1 个答案:

答案 0 :(得分:1)

为了使该工作具有响应性,我建议您将child-sub移到child之外,然后与visibility: hidden/visible一起移动一个负上边距(隐藏child你的边界),你可以直观地完成它。

Updated codepen

Stack snippet

.page {
  flex-direction: column;
  display: flex;
  align-items: center;
}

.parent {
  margin-top: 4px;
  padding: 5px;
  flex-direction: column;
  display: flex;
  align-items: center;
  border: 2px solid black;
}

.child {
  width: 100%;
  box-sizing: border-box;
  margin-top: 4px;
  border: 1px solid black;
  flex-direction: column;
  display: flex;
}

.child-sub {
  width: 100%;
  border: 1px solid black;
  border-top-color: white;
  margin-top: -1px;
  box-sizing: border-box;
  visibility: hidden;
}

.child-sub:hover,
.child:hover+.child-sub {
  visibility: visible;
  display: flex;
}
<div class="page">
  I want the parent div to NOT resize on child hover but the child div should resize. Can this be done with CSS?
  <div class="parent">Parent-div
    <div class="child">Child-div (Hover to display hidden div)
    </div>
    <div class="child-sub">Sub-menu</div>
  </div>
</div>