HTML CSS floats and inline-block issues

纵然是瞬间 提交于 2019-12-24 11:44:37

问题


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


回答1:


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.




回答2:


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 containerref




回答3:


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>



回答4:


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



来源:https://stackoverflow.com/questions/52718984/html-css-floats-and-inline-block-issues

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!