为什么浮动元素不能设置左右边距 [英] Why can't floated elements set their left and right margins

查看:844
本文介绍了为什么浮动元素不能设置左右边距的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在包装div中,浮动元素似乎不会响应左右边距设置。示例:

html:

 < div id =wrapper > 
< div id =content>< / div>
< / div>

css:

  #wrapper 
{
width:1000px;
display:block;
margin-left:auto;
margin-right:auto;
overflow:hidden;
}

#content
{
width:400px;
height:200px;
display:block;
float:left;
margin-left:30px;
}

#content忽略左边距设置。为什么?

解决方案

边距不会移动浮动元素,它们会推开内容。 b $ b

如果你想移动浮动元素,你可以给它下面的CSS规则:

  #content {
position:relative;
left:30px;
}

另一种方法是给元素一个透明边框:

  #content {
border-left:30px transparent;

如果您只是想定位div 在另一个div里面,然后使用绝对定位:

  #wrapper {
position:relative; / *必须为孩子的绝对定位* /
}

#content {
position:absolute;
剩下:0;
}


In a wrapper div, the floated elements don't seem to respond to left and right margin settings. Example:

html:

<div id ="wrapper">
    <div id = "content"></div>
</div>

css:

#wrapper
{
   width:       1000px; 
   display:         block;
   margin-left:         auto;
   margin-right:    auto;
   overflow:            hidden;
}

#content
{
   width:               400px;
   height:              200px;
   display:             block;
   float:               left;
   margin-left:         30px;
}

The #content ignores its left margin setting. Why?

解决方案

Margins do not move floated elements, they "push content away".

If you want to move the floated element, you could give it the following CSS rules:

#content {
    position: relative;
    left: 30px;
}

An alternative is giving the element a transparent border:

#content {
    border-left: 30px transparent;
}

If you are just looking to position a div inside of another div, then use absolute positioning:

#wrapper {
    position: relative; /* required for absolute positioning of children */
}

#content {
    position: absolute;
    left: 0;
}

这篇关于为什么浮动元素不能设置左右边距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆