csshtmlflexboxcss-shapespiano

How to create a completely flexible piano keyboard with HTML and CSS


I'm trying to create a piano keyboard that will keep its elements ratios using flex box, but can't seem to make the black notes stay the same width or height once I start changing the window size.

Here is a fiddle

body{
width: 800px;
height: 200px;
display: flex;
}

#kbd {

padding: 1%;
flex-flow: column;
display: flex;
flex: 4;
}

#keys {
display: flex;
flex: 8;
justify-content: center;
}


.note {
flex: 1;
display: inline-flex;
align-items: center;
}

.black {
justify-content: center;
position: absolute;
height: 45%;
background-color: #474747;
color: white;
width: 8%;
margin: 0 -4%; 
}

.white {
flex-flow: column;
justify-content: flex-end;
outline: 2px solid #474747;
color: #474747;
background-color: #ffffff;
padding-bottom: 1%;
}

Solution

  • Percentage height is calculated based on the height of the first positioned parent. In this case, the #keys and #kbd divs don't have a position CSS rule. This means the black keys are scaled based on the width of the body, instead of their direct parent.

    Add position: relative; to the #keys div to make it work properly.