Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

float element position changes elements alignments

I got some strange behavior of float, thought it could be a simple but I am new in css and learning why and how questions.

here when I apply float element to the button it changes element's horizontal center alignment to top not sure why.

Any help would be much appreciated.

<h2>Image Text</h2>
<p>Center text in image:</p>

<div style="border: 1px solid red;">
  Text on left
  <span><button style="height:40px;">test</button></span>
</div>

enter image description here

Now add

<span ><button style="height:40px;float:right">test</button></span>

enter image description here

I know this problem can be solved in many ways, I am just wondering about the strange behavior of these element with float.

Regards MK

like image 423
Mohsin khan Avatar asked Feb 16 '26 09:02

Mohsin khan


1 Answers

Adding height to the container is not the best solution because if the content changes, then the height must also be changed. overflow:auto; on the parent will work, but it introduces design limitations as well.

The issue you are running into has to do with containers not automatically clearing contained floats. You need to use something called a clearfix on the container. There are many methods but the one I usually use employs a pseudo-element and works back to ie8:

.clearfix::after {
  content: "";
  display: table;
  clear: both;
}

With that CSS rule in your style sheet, you can then just add the class="clearfix" to any containers that you need to clear its own children.

For more info about floats, this is a good article (scroll down to 'The Great Collapse,' to learn about this particular issue you are facing), and to learn more about clearfixes, this article explains how various clearfixes work.

The advantage of using a pseudo-element for the clearfix is that we don't have to change the actual parent element's style at all, while changes to the parent's style could conflict with design requirements (like adding overflow:auto; which would work, but might conflict with a design where we needed to use overflow:hidden; or overflow:visible; on that parent element):

Here is your code with clearfix applied (note that I moved your style rules to CSS and added classes instead of inline style, which is generally good practice):

.container {
  border: 1px solid red;
}
button {
  height:40px;
}
.float-right {
  float: right;
}
.clearfix::after {
  content: "";
  display: table;
  clear: both;
}
<h2>Image Text</h2>
<p>Center text in image:</p>

<div class="container clearfix">
  Text on left
  <span><button class="float-right">test</button></span>
</div>
like image 185
Veneseme Tyras Avatar answered Feb 17 '26 22:02

Veneseme Tyras



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!