讓兩個div 在同一列可以並行且填滿?

clipboard.png

這是兩個div

<div onclick="location.href='news';" class="news_other_layout" style="background-image: url('');">
</div>
<div onclick="location.href='news';" class="news_other_layout" style="background-image: url('');">
</div>
.news_other_layout{
 margin-top: 70px;
 position: relative;
 width: 50%;
 height: 300px;
 display: inline-block;
 object-fit: cover;
 background-repeat:no-repeat;
 background-size: cover;
}

但始終都無法兩個div填滿在同一排.....
他都會變上下

阅读 5.3k
5 个回答
<div onclick="location.href='news';" class="news_other_layout" style="background-image: url('');">
</div><div onclick="location.href='news';" class="news_other_layout" style="background-image: url('');">
</div>

更新一下。
你的代码里,两个div之间是有一个换行符的,当设置为inline-block元素时,如果父元素的font-size不是0,那这个换行符是会占一定空间的,导致这个父元素里的子元素总宽度是50% + 换行符宽度 + 50%,也就导致第二个div被挤到下面去。

所以解决方法是:

  1. 压缩html,去除换行;
  2. 父元素font-size设置为0,div重置font-size;
  3. 宽度设置为49%或更小。

另外,你们总是说要用Flex布局,但是又不问楼主(?)是否需要考虑兼容性,这样真的好嘛?怎么不说用Grid布局呢?

現在不是填滿在同排了嗎?

外面套一个父级div 使用flex布局

换行符导致的,使用float,或者在父级使用flex

你这边问题我遇到过,虽然你把div的display设置为inline-block了,但是很奇怪的是两个div标签之间的换行似乎还是要占用一些位置,导致虽然他们宽度是50%, 加一起是100%,但是依旧不能并排.你要把两个div标签之间的空格去掉.

比如这样:

<div onclick="location.href='news';" class="news_other_layout" style="background-image: url('');">
</div><div onclick="location.href='news';" class="news_other_layout" style="background-image: url('');">
</div>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题