David Somekh
David Somekh

Reputation: 933

CSS FlexBox - stretch child but not parent?

I have a DIV that has a child div which is displayed on hover.

Because I am using "visibility: hidden" the div is not stretched when the hidden div is displayed and nor does his parent.

What I am trying to achieve:

  1. The parent div should NOT stretch.
  2. The child div (Containing the hidden div) should stretch.

Is that possible using CSS without defining a static width?

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>

Upvotes: 1

Views: 1523

Answers (1)

Asons
Asons

Reputation: 87191

To make that work responsive, I suggest you move the child-sub outside the child and then, in combination with visibility: hidden/visible, a negative top margin (to hide the child's border), you can accomplish that visually.

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>

Upvotes: 3

Related Questions