【问题标题】:How to vertically align images without absolute positioning in a responsive layout如何在响应式布局中垂直对齐图像而无需绝对定位
【发布时间】:2014-12-10 02:23:59
【问题描述】:

我知道margin-left:auto;margin-right:auto; 使元素像text-align:center; 一样居中。

我的问题是关于垂直对齐。

我想保持我的图像与我的 vh 相关。

<section> 
  <div class="half">
    <img />
  </div>

  <div class="half">
    <img />
  </div>
</section>

风格:

.half {
height:100%;
width: 50%;
display:inline-block;
float:left;  
}

.half img {
max-width:93%;
max-height:90%;
}

关于小提琴的一个例子: http://jsfiddle.net/f16wpgpm/3/

【问题讨论】:

  • 我需要说display:tabledisplay:table-cell 方法不是我想要的,因为我需要使用我的vh 和vw 自动调整图像大小。看看我的例子:图像永远不会从屏幕上剪下来

标签: html css image position


【解决方案1】:

position:relative; 添加到.half,然后将以下CSS 添加到您的img 选择器:

margin: auto;
left: 0;
right: 0;
top: 0;
bottom: 0;

Updated Fiddle

【讨论】:

  • 不错。如果我需要像示例中那样让我的图像彼此靠近,而不是让它们水平居中怎么办? jsfiddle.net/f16wpgpm/3
【解决方案2】:

http://jsfiddle.net/f16wpgpm/6/

您可以为此使用display:tabledisplay:table-cell

section {
    display:table;
    width:100%;
}

.half {
    width: 50%;
    display:table-cell;
    vertical-align:middle;
}

【讨论】:

    【解决方案3】:

    您可以使用表格显示方法进行响应式垂直对齐。但是,这需要一个内部的&lt;div&gt; 充当要对齐的单元格:

    <div class="half first_half">
        <div class="inner">
            <img src="http://www.capitale-creativo.it/img/capcrea1.jpg" />
        </div>
    </div>
    

    然后通过将.half 显示为表格并将.inner 显示为其单元格,您可以像这样添加vertical-align: middle;

    .half{
        height:100%;
        width: 50%;
        display:table;
        float:left;
    }
    
    .inner{
        display: table-cell;
        vertical-align: middle;
    }
    

    它正在运行:http://jsfiddle.net/f16wpgpm/4/

    【讨论】:

      猜你喜欢
      • 2012-08-26
      • 1970-01-01
      • 2014-02-08
      • 1970-01-01
      • 2020-03-24
      • 2021-07-11
      • 1970-01-01
      • 2016-01-28
      • 1970-01-01
      相关资源
      最近更新 更多