Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
485 views
in Technique[技术] by (71.8m points)

html - Why do floats keep a "phantom" space when they escape to the next line?

I'm playing around with properties of CSS elements and wrote this code:

body {
    font-family: "Helvetica";
}
.parent {
    background-color: yellow;
    overflow: auto;
    padding-bottom: 20px;
    display: inline-block;
}
.col {
    height: 200px;
    padding: 20px 10px;
    float:left;
    margin: 10px 10px;
    }
.red {
    background-color: red;
}
.green {
    background-color: #00ff00;
}
.blue {
    background-color: #0000ff;
    color: white;
}
p:hover {
    background-color: #ffff00;
}

Why is it that when I run the result and resize the screen to the point where the blue float clears to the next line, the yellow outline of the parent div doesn't resize to fit the width?

I apologize if that is confusing. Here is a visual example of what I mean:

https://www.dropbox.com/s/9r7mhizfqdbyflh/Screenshot%202014-12-24%2001.02.36.png?dl=0

Why is there the yellow space left over despite it being inline-block? Is it because float keeps reserved space there even though it's cleared to the next line?

JSFiddle: http://jsfiddle.net/ffxg9qq0/1/embedded/result/

Thank you!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

the space was cause due to float:left of the children

you will need to write @media query so that the .parent adjusts

@media screen and (max-width: 400px){
    .col{
        float:none;
    }    
}

resize the below fiddle to max-width 400px

demo - http://jsfiddle.net/ffxg9qq0/3/

body {
  font-family: "Helvetica";
}
.parent {
  background-color: yellow;
  overflow: auto;
  padding-bottom: 20px;
  display: inline-block;
}
.col {
  height: 200px;
  padding: 20px 10px;
  margin: 10px 10px;
  float: left;
}
.red {
  background-color: red;
}
.green {
  background-color: #00ff00;
}
.blue {
  background-color: #0000ff;
  color: white;
}
p:hover {
  background-color: #ffff00;
}
@media screen and (max-width: 400px) {
  .col {
    float: none;
  }
}
<div class='parent'>
  <div class='col green'>
    <p>I'm in a green float!</p>
  </div>
  <div class="col red">
    <p>I'm in a red float!</p>
  </div>
  <div class="col blue">
    <p>I'm in a blue float!</p>
  </div>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...