Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't floated elements set their left and right margins

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?

like image 406
dave Avatar asked Jan 08 '11 01:01

dave


2 Answers

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;
}
like image 21
Marcus Whybrow Avatar answered Nov 15 '22 18:11

Marcus Whybrow


A more recent CSS technique that works perfectly in this scenario is to use the CSS transform property with a translate X or Y. This acts on the floated element only, so does not have the unintended effect of moving other elements around.

An example transform is this:

.floated-element {
  // move the floated element 10 pixels to the left
  transform: translateX(-10px);
}
like image 155
jacobedawson Avatar answered Nov 15 '22 20:11

jacobedawson