如何在没有表格的情况下对齐图像,文本和按钮的一行

时间:2018-11-09 03:48:43

标签: html css

我正在尝试将电影海报图像,说明文字对齐并在同一行上添加到购物车按钮。文本需要居中对齐,并且不能环绕按钮或图像。看起来应该像这样。

enter image description here

但是,使用我当前的代码,它看起来像这样。电影说明文字不是居中对齐,而是环绕在按钮周围。 enter image description here

这是我的代码。如何修改它以使其看起来像第一张图片?

    <div class="card-block">
        <div class="pull-left"><img src="https://{{movie.image}}" alt="[Image Missing]" width="70px" /></div>
        <br><span>{{movie.description}}</span>
        <span>
            <button class="float-right btn btn-sm btn-success" (click)="addToCart(movie)">
                Add to Cart
            </button></span>
    </div>

2 个答案:

答案 0 :(得分:1)

有很多方法可以解决您的问题。

您可以使用flex

 .container {
      display: flex;
      align-items: center;
     }
     
.container .item:nth-child(2){ /*Only second item padding and center text*/
  padding-left: 1em;
  padding-right: 1em;
  text-align: center;
}
    <div class="container">
      <div class="item">
          <img src="https://via.placeholder.com/80x100">
      </div>
      <div class="item">
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc sagittis sagittis enim. Nulla viverra aliquam.</p>
      </div>
      <div class="item">
          <button> Add to cart </button>
      </div>
    </div>

或者您可以尝试使用新的CSS-Grid,但某些浏览器尚不支持它

.container {
      display: grid;
      grid-template-columns: 1fr 4fr 1fr; /*Here you set how many columns will be and how much of the space they will take, for example there are 3 values, meaning 3 columns, the first and the last one will take 1 space of the row, and the second one will take 4 spaces*/
      align-items: center;
      grid-gap: 1em; /*The gap between items*/
    }
    
    .container .item:nth-child(2) {
       text-align: center;
    }
    <div class="container">
              <div class="item">
                  <img src="https://via.placeholder.com/80x100">
              </div>
              <div class="item">
                  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc sagittis sagittis enim. Nulla viverra aliquam.</p>
              </div>
              <div class="item">
                  <button> Add to cart </button>
              </div>
            </div>

答案 1 :(得分:0)

尝试改用flex,例如:

.wrapper {
  display: flex;
  flex-direction: row;
  align-items: center
}
p {
  text-align:center
}
<div class="wrapper">
  <img src="https://via.placeholder.com/150" />
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras sit amet est vel erat rutrum tempus. Etiam auctor dapibus magna, ut auctor metus pretium sed.
  </p>
  <button>
    Add
  </button>
</div>

希望获得帮助。