如何在CSS网格中居中图像?

时间:2018-04-24 20:08:17

标签: css css3 centering css-grid

如何让图像在左侧垂直居中,在右侧显示文字?



.pricing1box {
  display: grid;
  grid-template-columns: repeat(auto-fit, 300px);
  color: #444;
  margin-top: 150px;
  justify-content: center;
}

.pricing1box-div {
  background-color: orange;
  color: #fff;
  border-radius: 5px;
  font-size: 150%;
}

<div class="pricing1box">
  <div class="pricing1box-div">
    <img src="http://placehold.it/350x150.png" style="float: left; display: inline-block; width: 100px; vertical-align: middle;">
    <h6 style="color: black; padding: 10px;">Title</h6>
    <p style="font: 10px blue;">Powered by me</p>
    <br>
    <p>A dgdfg dfgdhdgfh fdgh dhdfg wertdfg dfgdh ergdfgd egr dfgdhd hdfh </p>
  </div>
</div>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:1)

您也可以在图像和文本上使用网格属性。只需将父级设为网格容器即可。

     cars.filter(function(car) {

        var fareType = car.data("fareType");
        var partnerCode = car.data("partnerCode");

        if (fareType == "DEAL" && partnerCode == "AV")
        {
            // get first instance only and move element to beginning of array
        }

        if (fareType == "DEAL" && partnerCode == "BU")
        {
            // also get first instance where partnerCode == BU only and move element to beginning of array 
           // If dataPrice is less than dataPrice for partner AV, move to first position, else move to second position
        }
    });
.pricing1box {
  display: grid;
  grid-template-columns: repeat(auto-fit, 300px);
  justify-content: center;  
  color: #444;
}

.pricing1box-div {
  display: grid;         /* new; nested grid container */
  grid-template-columns: 1fr 1fr;
  grid-template-rows: auto auto auto;
  background-color: orange;
  color: #fff;
  border-radius: 5px;
  font-size: 150%;
}

.pricing1box-div img {
  grid-column: 1;
  grid-row: 1 / -1;      /* from first line at start, to first line at end */
  align-self: center;    /* vertical centering */
  width: 100px;
}

.pricing1box-div :not(img) {
  grid-column: 2;
}

答案 1 :(得分:1)

您还可以混合flex&amp; grid以提高可读性

body {
  display: grid;
  grid-template-columns: repeat(auto-fit, 300px);
  justify-content: center;
  align-content: bottom;
}

div {
  display:flex;
  align-items: center; /* Vertical center of image & text */
  background-color: orange;
}

p {
  padding: 100px 10px; /* Demo stuff */
}
<div>
  <img src="//placecage.com/100/100">
  <p>text here</p>
</div>

答案 2 :(得分:0)

试试这个:

  position: relative;
  top: 50%;
  transform: translateY(-50%);

或者你可能只需要这个:align =“middle”

<img src="http://placehold.it/350x150.png" align="middle" style="float: left; display: inline-block; width: 100px; vertical-align: middle;">