Reputation: 566
HTML:
<html>
<head>
<link rel=stylesheet href='scarychildselector.css'>
</head>
<body>
<div></div>
<div></div>
<div>
<div></div>
<div></div>
</div>
</body>
</html>
CSS:
div{
height:50px;
width:50px;
}
div:nth-child(1){
float:left;
background-color:green;
}
div:nth-child(2){
float:right;
background-color:red;
}
Output in chrome:
I thought that the two green boxes will be in the left and the two red boxes will be in right of the window in an up-to-down manner
The problem here is that the last div floats to left instead of floating to right I'm confused what's the reason for floating to left? background-color property works fine and gives the div red color but the float property is'nt working. I just want to know why my code is behaving like that and why that box does'nt floats to the right
Upvotes: 1
Views: 485
Reputation: 4633
Your code and float actually work the same way as it was meant to be. The issue was in your understanding. What I am adding below is not a solution. I was trying to explain the way it works. Please check. Check the code now and comment the width: 150px;
and run again, so that you will understand the difference.
div {
display: inline-block;
width: 50px;
height: 50px;
margin: 10px;
}
div:nth-child(1) {
background-color: red;
float: left;
}
div:nth-child(2) {
background-color: green;
float: right;
}
.wrapper {
width: 150px; //Comment this line
}
<div></div>
<div></div>
<div class='wrapper'>
<div></div>
<div></div>
</div>
In order to align both the green boxes on one side and the red boxes on the other side, you need to give width: 100%
to the wrapper (The line you commented) and just comment the margin: 10px
. You can see it like below.
div {
display: inline-block;
width: 50px;
height: 50px;
}
div:nth-child(1) {
background-color: red;
float: left;
}
div:nth-child(2) {
background-color: green;
float: right;
}
.wrapper {
width: 100%;
}
<div></div>
<div></div>
<div class='wrapper'>
<div></div>
<div></div>
</div>
You were mistaken in giving width to the .wrapper
and since all the divs were of width 50px, the child divs will break into two lines. But floating was perfect. That's what I tried to illustrate in the first example.
Upvotes: 1