Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why a div with float: right does not respect the margin of the hr tag below?

I'm using twitter-bootstrap framework and I'm trying to put a form-control with some text aligned to the right and some text aligned the the left (all in the same line).

Here is the fiddle: http://jsfiddle.net/2gu29/3/

HTML

<div class="inlineb">Hello</div>
<div class="floatr inlineb">
    <input type="text" class="form-control inlineb"> cm
</div>
<hr>
<button class="btn btn-primary">Hello stackoverflow</button>

CSS

hr {
    margin: 30px 0px 30px 0px;
    border-color: red;
}
body {
    padding: 30px;
}
.form-control {
    width: 100px;
}
.floatr {
    float: right;
}
.inlineb {
    display: inline;
}

But, as you see, the div which contains the input above the hr tag, does not respect the margin setted to the hr in the css (margin-top: 30px) if I use float: right. But if I don't use this property, it respect it. see it: http://jsfiddle.net/2gu29/9/

Why my solution does not work? Could you give me an exmplanation, please? Do you have another alternative to do it?

Any tip, advice or help will be appreciated, and if you need more info, let me know and I'll edit the post.

like image 527
mllamazares Avatar asked Dec 12 '22 09:12

mllamazares


2 Answers

This is always a problem with floated element and inline element. If you want to fix this issue then you need to add display:inline-block and width:100% in hr tag. Here is updated fiddle

like image 185
Viken Patel Avatar answered Dec 17 '22 22:12

Viken Patel


The float CSS property specifies that an element should be taken from the normal flow and placed along the left or right side of its container, where text and inline elements will wrap around it.

If you read this line from MDN Float Documentation you can understand that whenever we apply float property to any element, it is taken out from normal flow of the page.

Hence, margin is getting calculated from the Hello word instead of floated element.

Solution

Wrap the divs inlineb and floatr in another div and you should be fine. Checkout this JS Fiddle

Updated Code

<div class='container'>
  <div class="inlineb">Hello</div>
  <div class="floatr inlineb">
    <input type="text" class="form-control inlineb" /> cm
  </div>
</div>
<hr>
<button class="btn btn-primary">Hello stackoverflow</button>
like image 28
Sachin Avatar answered Dec 18 '22 00:12

Sachin