Home > Enterprise >  Block element after a float element ignores margin-top property
Block element after a float element ignores margin-top property

Time:01-16

I have a h1, img and div tag in a div tag. The img tag I have assigned a float: left;. And the div tag a clear: both;. Since I want to have a space between the image and the div tag, I have also assigned a margin-top to the div tag.

Problem: However, the margin is not interperated.

Question: Why is that? And what do I have to do to insert a space?

* {
  margin: 0;
  padding: 0;
}
body {
  background: black;
}

.block {
  background: white;
  padding: 10px;
  display: flow-root;
}

.block img {
  width: 300px;
  text-align: right;
  
}

.leftFloat {
  float: left;
  margin-right: 10px;
}

.user-interaction-btns {
  margin-top: 20px; /* this margin doesnt work, why? */ 
  display: flex;
  clear:both;
  background: purple;
}
<div >
  <h1>Title lorem ipsum </h1>
  <img  src="https://via.placeholder.com/300">
  lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum.
  
  <div >
    <button>Action</button>
  </div>
  
</div>

CodePudding user response:

This is because the margin top does not refer to the image but to the text above. An easy fix for your problem would be to add a margin-bottom: 10px; to the image.

CodePudding user response:

Floating Elements is old and comes with some quirks and hacks. Flex-box was introduced in 2009 and is now support by all web browsers, it's responsive and mobile friendly. It has all the benefits of float but without having to implement hacks. Below I have swapped from your float approach and used flex instead.

.img-text-container {
  display: flex;
  gap: 10px;
}

.user-interaction-btns {
  margin-top: 20px;
}
<div >
  <h1>Title lorem ipsum </h1>

 <div >
    <img  src="https://via.placeholder.com/300">
    <div >
    lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum.
    </div>
 </div>
  
  <div >
    <button>Action</button>
  </div>
  
</div>

  • Related