Float:; not working CSS

Asked

Viewed 77 times

2

I intend to align these blocks in a horizontal line, but the use of the float:; is not meeting the expected, what mistake I am making?

.fl > div{ float:left;  }

div:nth-child(1){ position:relative; width:300px; height:300px; background-color:#066;}	
div:nth-child(2){ position:relative; width:300px; height:300px; background-color:#06F;}	
div:nth-child(3){ position:relative; width:300px; height:300px; background-color:#C30;}	
<div class="fl">
<div class="bk">1</div>
<div class="bk">2</div>
<div class="bk">3</div>

</div>

2 answers

3

Because the . Fl has the same size as the other Divs 300px.

Better to use like this:

.fl {width: 100%;}
.fl .bk {float: left;}

.bk:nth-child(1){ position:relative; width:300px; height:300px; background-color:#066;} 
.bk:nth-child(2){ position:relative; width:300px; height:300px; background-color:#06F;} 
.bk:nth-child(3){ position:relative; width:300px; height:300px; background-color:#C30;}

<div class="fl">
    <div class="bk">1</div>
    <div class="bk">2</div>
    <div class="bk">3</div>
</div>
  • Without specifying the size of '.Fl ' works tbm, the good thing is that it worked with display:flex; also

  • 1

    Yes, it works. It depends a lot on its purpose. But it would still indicate instead of using px in . bk would use percentage.

3


Your dial is wrong. It should be:

.fl > div{ float:left; }

.fl div:nth-child(1){ position:relative; width:300px; height:300px; background-color:#066;}	
.fl div:nth-child(2){ position:relative; width:300px; height:300px; background-color:#06F;}	
.fl div:nth-child(3){ position:relative; width:300px; height:300px; background-color:#C30;}	
<div class="fl">
   <div class="bk">1</div>
   <div class="bk">2</div>
   <div class="bk">3</div>
</div>

At setting div:nth-child(1) you are selecting your own div .fl. If you want to select the children of .fl, add .fl on the selectors nth-child().

Explanation:

Like div is a generic selector, will select all, regardless of level:

<div class="fl"> nth-child(1)
   <div class="bk">1</div> nth-child(1)
   <div class="bk">2</div> nth-child(2)
   <div class="bk">3</div> nth-child(3)
</div>

See that there are two nth-child(1), soon the div .fl will have the same styles in:

div:nth-child(1){ position:relative; width:300px; height:300px; background-color:#066;}

Soon the divs within .fl will not stand side by side because the div .fl has the same width width of 300px.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.