Home > database >  CSS - Problem with float parameter only stacking sections on top of one another
CSS - Problem with float parameter only stacking sections on top of one another

Time:04-23

Having an issue with the float parameter so made a simple code snippet to show the problem (sure it's something simple but can't pinpoint it).

As I understand the float declaration it should:

  • move the first section up and to the left or right
  • the next section should move up and to the left or right next to the first section as long as there is still enough width space
  • Above should continue until width space is not available and a new row has to be made

However, the sections are only stacking one on top of the other and to the side designated in the declaration. Can't get them to move next to one another.

header,
footer {
  text-align: center;
  height: 30px;
  width: 100%;
  border: 1px solid black;
  clear: both;
}

section {
  text-align: center;
  height: 30px;
  width: 20%;
  float: left;
  border: 1px solid black;
  clear: both;
}
<header>Header</header>
<section>Section 1</section>
<section>Section 2</section>
<section>Section 3</section>
<footer>Footer</footer>

CodePudding user response:

The problem is the "clear" rule you can proceed in two ways:

Solution 1:

If you want to use the "clear" style rule this will have to be applied to a parent containing (div in the example) section with "float":

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="index.css" />
    <title>Document</title>
</head>
<body>
    <header></header>
    <div id="parent">
        <section></section>
        <section></section>
        <section></section>
    </div>
    <footer></footer>
</body>

</html>

css header, footer { height: 100px; width: 100%; border: 1px solid black; clear: both; }

    #parent {
        clear: both; /* add this here and remove clear:both from section */
    }

    section {
        height: 300px;
        width: 20%;
        float: left;
        border: 1px solid black;
    }

in this way the row containing the section tags will be aligned and everything that comes after will not be moved based on the positions given by the "float". The clear property is used to prevent other floated elements from appearing alongside an element. It applies only to block elements and is not inherited.

Solution 2

Only remove the clear:both from section in the css

CodePudding user response:

Using clear: both on your sections is forcing them to go on new lines instead of stacking next to each other.

If you remove that and only apply clear: both to your footer, it should work correctly.

  • Related