Responsive web design by making a piano -step 17

I am a bit confused here, how does floating the “key” element make the elements arrange horizontally when they were arranged vertically.


<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Piano</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="./styles.css">
  </head>
  <body>
    <div id="piano">
      <div class="keys">
        <div class="key"></div>
        <div class="key black--key"></div>
        <div class="key black--key"></div>
        <div class="key"></div>
        <div class="key black--key"></div>
        <div class="key black--key"></div>
        <div class="key black--key"></div>

        <div class="key"></div>
        <div class="key black--key"></div>
        <div class="key black--key"></div>
        <div class="key"></div>
        <div class="key black--key"></div>
        <div class="key black--key"></div>
        <div class="key black--key"></div>

        <div class="key"></div>
        <div class="key black--key"></div>
        <div class="key black--key"></div>
        <div class="key"></div>
        <div class="key black--key"></div>
        <div class="key black--key"></div>
        <div class="key black--key"></div>
      </div>
    </div>
  </body>
</html>
html {
  box-sizing: border-box;
}

*, *::before, *::after {
  box-sizing: inherit;
}

#piano {
  background-color: #00471b;
  width: 992px;
  height: 290px;
  margin: 80px auto;
  padding: 90px 20px 0 20px;
}

.keys {
  background-color: #040404;
  width: 949px;
  height: 180px;
  padding-left: 2px;
}

.key {
  background-color: #ffffff;
  position: relative;
  width: 41px;
  height: 175px;
  /* float:left; */
  margin:2px;
}

By default, since the keys are divs then they stack on top of each other because there is an implied newline at the end of each div. Before you add the float, if you add a border to .key then you will see them stacked up on the left.

Floating them is an old-school method (before we had flexbox or grid) to get block-level elements to line up side by side instead of stacking on top of each other. I don’t think most people would use floats this way nowadays (you can accomplish the same thing with flexbox), but perhaps the purpose here is just to make you aware that the float property exists.

The primary use of float today is to allow text to wrap around an element. For example, if you had an image on the side of the page and you wanted the text to hug the image. There are some examples at the link below.

The CSS Float Property: How to Use & Clear It

3 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.