0

Learning CSS basics and was doing layouts with floats. I know CSS Grid and Flexbox are best practice and I intend to learn them, but wanted to understand the basics of floats before I move on.

body {
  margin: 0px;
  padding: 0px;
}

.wrapper {
  width: 600px;
  padding-left: 200px;
  padding-right: 200px;
  overflow: hidden;
}

.col-main {
  float: left;
  width: 100%;
}

.col-left {
  position: relative;
  float: left;
  width: 200px;
  margin-left: -100%;
  right: 200px;
}

.col-right {
  float: left;
  width: 125px;
  margin-right: -125px;
}
<body>
  <div class="wrapper">
    <div class="col-main">Main Content</div>
    <div class="col-left">Left Content</div>
    <div class="col-right">Right Content</div>
  </div>
</body>

On an intuitive level I understand how .col-left works. margin-left: -100%; represents 600px width of the parent element placing it along side .col-main and position: relative; combined with right: 200px; puts it flush within the reserved left padding of the parent element. In fact, it doesn't have to be -100% it can be -200% if you like and push .col-left completely off the screen.

However, I cannot grasp how .col-right works. Having a negative value in margin-right that's equal to the absolute value in width places the .col-right on the same line, neatly sticking out on the right side of the parent element. It's great but I don't understand how or why. What's more, is that if you change margin-right to -200px or heck even -1000px it will still be in the same position. Why?

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
  • the total width of all the elements (including their margin) need to be 100%. col-main is already having 100% so we need negative margin to keep the total 100% – Temani Afif Apr 10 '22 at 15:35
  • even if I agree it's good to learn float, this example is not the best. This is a hacky and very very old way to create layouts that no one should use. If you found it online, check the date of the article to notice it's maybe 2000 or so – Temani Afif Apr 10 '22 at 15:37
  • The author mentioned that it's an old way of doing layouts. – thesnowplow Apr 10 '22 at 17:47

1 Answers1

0

Float's meaning is basically floating :). You can insert value How much you want. But in the end it floats to right. Because wrapper's width not enough to changing to your see. if you add more width to wrapper and specify scalable value to .col-main (like 50px). You can see more understandable. Because .col-right is in over .col-main. like z-index shits

Kaan Kuscu
  • 41
  • 5