Issue
I can not understand how css works, and it's annoying me. I was trying to do some basic side by side two divs and one div below them. At first I've learned that I had to give float:left for both side by side divs. For curiosity I did'nt gave float:left for the second side by side div, and I came across this layout:
(source: imge.to)
Then I gave float:left for the second side by side div, and I came across this layout:
(source: imge.to)
Question: I didn't gave float:left for third div but it didn't act like the first screen shot. Why?
css code:
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.container {
width: 1000px;
margin-left: auto;
margin-right: auto;
}
.blog-posts {
width: 50%;
background-color: #0000ff;
float: left;
}
.other-posts {
width: 25%;
background-color: #00ff00;
float: left;
}
.author-text {
background-color: #ffff00;
}
html code:
<div class="container">
<div class="blog-posts">dend endje denjde akdlsd gsjgıdg sadsujrg spsadnajd asdnsajdd</div>
<div class="other-posts">extra dummy text</div>
<div class="author-text">author text</div>
</div>
Solution
When you use a float, you break the natural box-model
behavior of the markup.
Your first floated element has a width of 50%, relative to the parent (1000px) it will take the half of the .container
. The second (floated) element will take the next 250px. And here comes the good thing.
The third element, which isn't floated, is also a div
, thus a block-level element (so implicitly it will take 100% of the width of its parent). If you set the background-color
of your first and second element to a transparent one #0000ff00
and #00ff0000
respectively. You will see your third element is growing behind them.
This is, what I mean with "breaking the box-model". Now, to understand this beter, you could start giving a explicit width
to the third element. Let's say: 90%
, you will see how the yellow background will reduce itself from the right side.
If you set the width
to 50%
it will "jump" down, to the second line. It will be even broad as the first element, but two times height. With other words, it will try to fit in the first available space.
To avoid this, in the past, we used the clearfix hack... but since flexbox and css grids are broadly supported, we don't have to rely in floats anymore for this side-by-side layouts.
Float has their own use cases, is not that float sucked, it's just not meant for layout.
For more information on this topic you can check this great article about floats on CSS-Tricks.
Answered By - f-spin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.