没有pos的垂直中心图像:绝对内部pos:相对

时间:2016-09-29 03:21:32

标签: html css

我博客的标题显示标题后面有一个图片。我希望此图片具有自己的高度,直到大于50vh(用户视口的50%)。

但正常行为是从底部裁剪图像,我希望从顶部底部裁剪图像(换句话说:我希望图像垂直居中)。

我可以使用top: 50%; transform: translateY(-50%)执行此操作,但在这种情况下img应为position: absolute,这会使标题始终具有相同的高度(因为图像无法设置)元素的高度)。

这是我的代码:

<div class="header">
  <div class="date">
    Posted 10 hours ago
  </div>

  <h1>Meet the all new Jaguar F-type</h1>

  <img src="http://read.bi/2cMrdUI" />
</div>

在以下示例中,请尽可能调整jsfiddle width 。这将更容易理解。

  

https://jsfiddle.net/jkc3L13g/

&#13;
&#13;
.header {
    max-width: 100%;
    position: relative;
    overflow: hidden;
    min-height: 150px;
    max-height: 70vh;
    .date {
      z-index: 10;
      position: absolute;
      top: 0;
    }
    h1 {
      position: absolute;
      bottom: 0;
      z-index: 10;
    }
    img {
      width: 100%;
      height: auto;
    }
}

/* Just to style.. */
body { font-family: sans-serif; }
.header { color: white; text-shadow: black 0 1px 2px }
hr { margin: 2rem 0 ; }
code { font-size: 1.25rem; padding: 1px 2px; background: lightyellow; }
h1, .date { margin: 10px }
&#13;
<div class="header">
  <div class="date">
    Posted 10 hours ago
  </div>

  <h1>Meet the all new Jaguar F-type</h1>
            
  <img src="http://read.bi/2cMrdUI" />
</div>

<hr />

<p>
Resize window width as much as you can.
</p>
<p>
When <code>img</code> gets too big and <code>.header</code> starts limitating to <code>70vh</code>, <code>img</code> should "vertically centralize".
</p>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

而不是<img>代码,将图片用作.header的CSS背景图片,然后设置background-size: coverbackground-position: center(这将对齐图片),但是你还需要为.header设置固定的高度。

这看起来会有所不同,希望它可以帮到你。

background-image: url(http://read.bi/2cMrdUI);
background-size: cover;
background-position: center;

JSFiddle:https://jsfiddle.net/jkc3L13g/1/

.header {
  max-width: 100%;
  position: relative;
  overflow: hidden;
  min-height: 150px;
  height: 70vh; /* fixed height */

  background-image: url(http://read.bi/2cMrdUI);
  background-size: cover;
  background-position: center;

  .date {
    z-index: 10;
    position: absolute;
    top: 0;
  }
  h1 {
    position: absolute;
    bottom: 0;
    z-index: 10;
  }
  img {
    width: 100%;
    height: auto;
  }
}

/* Just to style.. */
body { font-family: sans-serif; }
.header { color: white; text-shadow: black 0 1px 2px }
hr { margin: 2rem 0 ; }
code { font-size: 1.25rem; padding: 1px 2px; background: lightyellow; }
h1, .date { margin: 10px }
<div class="header">
  <div class="date">
    Posted 10 hours ago
  </div>

  <h1>Meet the all new Jaguar F-type</h1>

</div>

<hr />

<p>
  Resize window width as much as you can.
</p>
<p>
  When <code>img</code> gets too big and <code>.header</code> starts limitating to <code>70vh</code>, <code>img</code> should "vertically centralize".
</p>