图像未出现在显示的同一行:内联块

时间:2016-04-30 06:43:52

标签: html css

为了将两个图像彼此相邻(即两个图像在同一行上),我尝试了以下代码:

<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,则图像会出现在同一行上。这是为什么?

6 个答案:

答案 0 :(得分:1)

删除img代码之间的新行:

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

这是因为使用inlineinline-block声明的元素对空格敏感。

更多信息:on David Walsh's Blog

通常使用浮点数或弹性框来完成布局。

<强>浮筒

/* 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>

<强> Flexbox的

.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>

答案 1 :(得分:0)

试试这段代码

#container {
            max-width:100%;
            display:flex;
        }

        img {
            flex:1;
        }

答案 2 :(得分:0)

使用css float属性:

  img {
        width:50%;
        float:left;
    }

fiddle。不需要显示。

答案 3 :(得分:0)

align property提供给图片。

 <img src="Google-logo.png" align="left">
 <img src="Google-logo.png" align="left">

https://jsfiddle.net/bt2341yh/

答案 4 :(得分:0)

根据上述解决方案,将页面保持在下一行内容旁边是非常困难的。它看起来像我们代码的缩小版本。因此,请尝试在父元素font-size:0上添加#container。这将解决此问题。

#container { 
   width:100%;
   font-size:0;
}

DEMO

答案 5 :(得分:0)

图像给出边距和填充,因此给出50%的宽度不会使它们排成一行。尝试减小宽度或添加float:left

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