gpt4 book ai didi

html - 没有 pos 的垂直居中图像 :absolute inside pos:relative

转载 作者:行者123 更新时间:2023-11-28 05:07:34 26 4
gpt4 key购买 nike

我博客的标题显示标题后面有一张图片。我希望这张图片有自己的高度直到它变得大于50vh(用户视口(viewport)的 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 宽度。这样会更容易理解。

https://jsfiddle.net/jkc3L13g/

.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 }
<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>

最佳答案

而不是 <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>

关于html - 没有 pos 的垂直居中图像 :absolute inside pos:relative,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39760886/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com