【问题标题】:Center image vertically in div using only css [duplicate]仅使用css在div中垂直居中图像[重复]
【发布时间】:2018-03-28 13:49:38
【问题描述】:

我正在尝试将包含在显示设置为表格的 div 中的图像居中。在其中,我希望显示一个图像,它应该位于垂直和水平的中心。我已经使用 margin:auto 实现了水平位置并将其设置为 display: table-cell,但它没有垂直居中。任何帮助都会很棒

.overlay { height: 50%; background: red;position: fixed;
top: 0;
left: 0;
height: 50%;
width: 100%;
display: table;}
.swipe {height: 80px;
display: table-cell;
margin: auto;}
<div style="height:300px">
<div class="overlay">
   <img class="swipe" src="https://d30y9cdsu7xlg0.cloudfront.net/png/255751-200.png" />

【问题讨论】:

    标签: html css


    【解决方案1】:

    在顶部和底部使用填充

    .overlay { background: red; position: fixed;
    top: 0;
    left: 0;
    padding: 5% 0 5% 0;
    width: 100%;
    display: table;}
    .swipe {height: 80px;
    display: table-cell;
    margin: auto;}
    <div style="height:300px">
    <div class="overlay">
       <img class="swipe" src="https://d30y9cdsu7xlg0.cloudfront.net/png/255751-200.png" />

    【讨论】:

      【解决方案2】:

      我建议给 .overlay &lt;div&gt; 一个 flexbox layout 而不是一张桌子。然后您可以通过简单地将三个规则应用于父级来使图像居中:

      .overlay {
        display: flex;
        align-items: center;
        justify-content: center;
      }
      

      请注意,.swipe 上不再需要 display: table-cellmargin: auto

      这可以在下面的例子中看到:

      .overlay {
        height: 50%;
        background: red;
        position: fixed;
        top: 0;
        left: 0;
        height: 50%;
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
      }
      
      .swipe {
        height: 80px;
      }
      <div style="height:300px">
        <div class="overlay">
          <img class="swipe" src="https://d30y9cdsu7xlg0.cloudfront.net/png/255751-200.png" />
        </div>
      </div>

      希望这会有所帮助! :)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-04-08
        • 1970-01-01
        • 2014-03-06
        • 2011-10-06
        • 1970-01-01
        • 2013-04-05
        • 2016-03-06
        • 2013-03-29
        相关资源
        最近更新 更多