margin-top under a floated div css

2020-07-10 08:31发布

I have a div under a float:right div. For some reason, the top margin cannot be applied to the first div. here is the css

#over{
  width:80%;
  float:right;
  color:#e68200; 
 }

#under{
  clear:both;
  background:url(../images/anazitisi.png) no-repeat;  
  margin:10px auto; /*does not work!!!*/
  width:95px;
  height:20px;
 } 

does anyone know what's going on?

标签: css margin
3条回答
Ridiculous、
2楼-- · 2020-07-10 08:43

Floated things are kind of floated out of the normal layout, so generally don't affect other things that aren't floated like them. Of course the float behaviour in different browsers differs, but that's the general idea.

After the floated div you'd need something (like an empty div) that will clear the float (has style="clear:both;").

However, like I said, browser behaviour will still vary, on where it then decides the margin should be counted from. There are of course workarounds for that. See this page for more on that.

查看更多
何必那么认真
3楼-- · 2020-07-10 08:44

try this css snipe, i think this will solve your problem.

  #over{
  width:80%;
  float:right;
  color:#e68200; 
  background-color:#234fdd;
  height:auto;
  margin-bottom:30px;
}

#under{
 clear:both;
 background:url(../images/anazitisi.png) no-repeat;  
 margin:auto;
 width:200px;
 height:20px;
 background-color:#23ffff;
} 
查看更多
乱世女痞
4楼-- · 2020-07-10 08:53

A solution without extra <div>

What you see, is the problem of collapsing vertical margins in CSS3. This problem will be more easily solved with the advent of CSS4. In the mean time, it is not a good idea to add an extra <div>, as easy as it may sound. It is generally better to keep content and presentation strictly separated.

Here is how I solved this issue on my website. The solution exploits the absence of vertical margin collapse inside inline blocks.

#under should contain at least the following items:

#under {
    clear: both;
    display: inline-block;
    width: 100%;
}
查看更多
登录 后发表回答