为了将两个图像彼此并排放置(即,两个图像位于同一行),我尝试了以下代码:

<html>
<head>
    <style>

        #container {
            width:100%;
        }

        img {
            display:inline-block;
            width:50%;
        }

    </style>
</head>

<body>
    <h1 style="text-align:center"><strong>Test</strong></h1>
    <div id="container">
        <img src="Google-logo.png">
        <img src="Google-logo.png">
    </div>
</body>




容器div的宽度应该由两个图像平均分配,对吗?但是,这不会发生,并且图像显示在两行中。

但是,如果我改用float:left,则图像确实出现在同一行上。为什么是这样?

最佳答案

删除img标记之间的新行:

<div>
    <img src="..." alt=""><img src="..." alt="">
</div>


发生这种情况是因为用inlineinline-block声明的元素对空格敏感。

更多信息:on David Walsh's Blog

通常,布局是用float或flexbox代替的。

浮点数



/* Clearfix */
.wrapper:after {
  content: '';
  display: table;
  clear: both;
}

.item {
  float: left;
  width: 50%;
  height: 100px;
}

.item-1 {
  background: red;
}

.item-2 {
  background: blue;
}

<div class="wrapper">
  <div class="item item-1"></div>
  <div class="item item-2"></div>
</div>





弹性盒



.wrapper {
  display: flex;
}

.item {
  flex: 1; /* Or use width: 50%; */
  height: 100px;
}

.item-1 {
  background: red;
}

.item-2 {
  background: blue;
}

<div class="wrapper">
  <div class="item item-1"></div>
  <div class="item item-2"></div>
</div>

09-11 17:44
查看更多