HTML DIV没有水平对齐

时间:2019-02-26 09:48:15

标签: html css

我一直在尝试使用CSS将3个html div水平对齐,我使用了display: inline-block,但是它不起作用。我还尝试将div包装器更改为无序列表,并且确实将其水平对齐,但是每次尝试对 + 符号设置样式时,div对齐都会恢复为垂直对齐。请检查下面的代码,让我知道最佳的解决方案。

使用div作为包装的HTML

#freqboughtwrapper {
  display: inline-block;
  width: 100px;
}

.freqitem1 {
  min-height: 50px;
  background: url('acer1.jpg')no-repeat;
  background-size: 50px 50px;
}

.freqitem2 {
  min-height: 50px;
  background: url('hdmi1.jpg')no-repeat;
  background-size: 50px 50px;
}

.freqitem3 {
  min-height: 50px;
  background: url('monitor1.jpg')no-repeat;
  background-size: 50px 50px;
}
<h3>Frequently bought together</h3>
<div id="freqboughtwrapper">
  <div class="freqitem1"></div> +
  <div class="freqitem2"></div> +
  <div class="freqitem3"></div>
</div>

使用ul作为包装器的HTML

#freqboughtwrapper {
  display: inline-block;
  width: 100px;
}

.plussign {
  size: 10px;
}

.freqitem1 {
  min-height: 50px;
  background: url('acer1.jpg')no-repeat;
  background-size: 50px 50px;
}

.freqitem2 {
  min-height: 50px;
  background: url('hdmi1.jpg')no-repeat;
  background-size: 50px 50px;
}

.freqitem3 {
  min-height: 50px;
  background: url('monitor1.jpg')no-repeat;
  background-size: 50px 50px;
}
<h3>Frequently bought together</h3>
<ul id="freqboughtwrapper">
  <li>
    <div class="freqitem1"></div>
    <p class="plussign"> + </p>
  </li>
  <li>
    <div class="freqitem2"></div>
    <p class="plussign"> + </p>
  </li>
  <li>
    <div class="freqitem3"></div>
  </li>
</ul>

3 个答案:

答案 0 :(得分:0)

通过这种方式使用flex-box:

.freqboughtwrapper{
  display: flex;
  flex-flow: row;
  align-items: center;
  justify-content: space-between; //if you want them equally spaced out and spread out.
  justify-content: space-evenly; // If you want them on equal distance from boundary and each other
}

答案 1 :(得分:0)

您需要使用flex选项

.divclass
{
     display:flex;
}

您可以在此处获得简短的教程 https://css-tricks.com/snippets/css/a-guide-to-flexbox/

答案 2 :(得分:0)

我建议保持它使用div作为包装器。如果您在display: flex上包括display: inline-block而不是#freqboughtwrapper,它应该为您提供所需的布局。

此外,您还提到了+号的样式,您可能需要将其包装在div中,以便可以仅定位此图标。 (取决于您想要的样式)。

#freqboughtwrapper {
  display: flex;
  align-items: center;
  min-width: 100px;
}

.freqitem1 {
  min-height: 50px;
  width: 50px;
  background: url('https://via.placeholder.com/50x50')no-repeat;
  background-size: 50px 50px;
}

.freqitem2 {
  min-height: 50px;
  width: 50px;
  background: url('https://via.placeholder.com/50x50')no-repeat;
  background-size: 50px 50px;
}

.freqitem3 {
  min-height: 50px;
  width: 50px;
  background: url('https://via.placeholder.com/50x50')no-repeat;
  background-size: 50px 50px;
}
<h3>Frequently bought together</h3>
<div id="freqboughtwrapper">
  <div class="freqitem1"></div> +
  <div class="freqitem2"></div> +
  <div class="freqitem3"></div> +
</div>

相关问题