简体   繁体   中英

HTML CSS floats and inline-block issues

There are three blocks, first and last one are floated left and the middle one is displayed inline-block and cleared both. Why my middle block is coming at the end? Here is my code.

 .box { width: 200px; height: 200px; background: red; } .block { height: 200px; width: 200px; background: blue; display: inline-block; clear: both; } .box1 { float: left; } .box2 { float: left; background: green; }
 <div class="box box1">1st Block</div> <div class="block">Middle Block</div> <div class="box box2">Third block</div>

https://codepen.io/suraj_122/pen/EdZpag

All float elements placed from left first one after the other and then other unfloated elements are placed

if you want the block element to be in middle

then make this .box1{ float:left;} .box2{ float:right;}

and then automatically the inline block element will come to center.

i suggest you to make all the elements inline block itself as they are all same width and height.it is best way for responsive design also.

clear property applies to only block level elements, so adding it to the inline-block won't have any effect and will not clear float as you expect.

在此处输入图片说明

https://developer.mozilla.org/en-US/docs/Web/CSS/clear


The float CSS property specifies that an element should be placed along the left or right side of its container, allowing text and inline elements to wrap around it . The element is removed from the normal flow of the web page, though still ref


inline-block

This value causes an element to generate an inline-level block container ref

Remove css in middle box "display: inline-block;clear: both;" and add " float:left"

 .box { width: 200px; height: 200px; background: red; } .block { height: 200px; width: 200px; background: blue; /* display: inline-block; clear: both; */ float:left; } .box1 { float: left; } .box2 { float: left; background: green; }
 <div class="box box1">1st Block</div> <div class="block">Middle Block</div> <div class="box box2">Third block</div>

You can remove the inline-block from the middle block (.block) and rap it all inside new div that row's it all. Just like this:

CSS:

.rowed {
  display: -ms-flexbox;
  display: flex;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
}

HTML:

<div class="rowed">
  <div class="box box1">1st Block</div>
  <div class="block">Middle Block</div>
  <div class="box box2">Third block</div>
</div>

** Just like Bootstrap are doing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM