gpt4 book ai didi

html - 如何使用 html 和 css 缩放(外部)元素与(内部)img 元素相同?

转载 作者:太空宇宙 更新时间:2023-11-04 01:27:32 25 4
gpt4 key购买 nike

我的目标是对齐 <h1><img> 底部的顶部和旁边使用 CSS 和 HTML。当您缩放窗口时,图像的大小会增加(垂直和水平),我希望文本在图像顶部对齐,紧跟底线。目前我使用一定百分比的宽度和高度来对齐文本,但您永远不知道文本是否真的会在底部对齐。

我还提供了一个具有预期结果的示例。蓝色文本与底部对齐的红色框是我想要完成的,我使用了一个具有可变高度和宽度的元素。

因此我想是否可以缩放 <img> 的容器与图像本身成比例,我可以获得相同的结果。

一些额外的信息

  • 不想使用 css 网格
  • 不知道我的应用程序中图像的比例。

我有以下css和html

container{
position:relative;
height:100%;
}
img{
position: absolute;
width:100%;
height:auto;
z-index:1;
}
h1{
position:absolute;
top:30vw;
left:50vw;
color:red;
z-index:10;
}

.variable-container{
position:relative;
text-align:center;
height:70vw;
width:50vw;
background-color:#de2d3d;
}
h2{
width:100%;
position:absolute;
bottom:10px;
color:blue;
}
<div class="container">
<h1>Title</h1>
<img src="https://placebear.com/g/200/100.jpg">
</div>


<!-- This is what I am trying to accomplish -->
<div class="variable-container">
<h2>
Aligned bottom of box
</h2>
</div>

最佳答案

所以这里的主要问题是嵌套的 img 元素已被定位为 absolute将其从正常文档流中取出。因此,外部元素(包含父元素)无法根据内部元素(嵌套元素)进行缩放,因为它不再与文档流相关。

变更摘要:

嵌套 img 元素的定位:

  • 嵌套的 img 元素 position 属性从 absolute 更改对于 relative,此属性可能会被完全删除(如在此范围内似乎没有必要)

嵌套h1元素的定位:

  • 嵌套的 h1 元素的定位也已重新设计,以水平居中一个绝对定位元素你可以总是简单地用单位声明 leftright 属性0 的值,并且由于 h1 是一个 block 元素,只需声明text-align: center 使文本居中。

  • 为了相对于包含元素的一致定位,使用bottom 属性而不是 top 属性;自从要求是让这个元素保持相对于包含元素的底部。如果要求对立(相对于包含的顶部定位元素),然后使用 top 属性将是适用的。

图片纵横比问题:

  • 第一个示例演示了图像宽高比的一些问题,所以还有一个 background-image 替代品可以称为好吧。

代码片段演示:

注意:为了演示,您可以手动调整包含元素(右下角)的大小。

.container{
position:relative;
height:100%;
}
img{
position: relative; /* to scale outer el same as inner el, inner el can't be out of normal document flow */
width:100%;
height:auto;
z-index:1;
}
h1{
position:absolute;
/* rather use `bottom` property if text needs to stay at bottom, and use an absolute unit value like `px` for most consistent positioning */
bottom:30px;
/* simply center an absolutely positionied element with properties `left` & `right` with values of `0` */
left:0;
right: 0;
text-align: center; /* then center text of block element */
color:red;
z-index:10;
margin: auto; /* unset vendor margin property */
}

.bg-img {
background-image: url(https://placebear.com/g/200/100.jpg);
background-size: cover;
height: 100%;
}

/* For the sake of demonstration */
.resize-demonstration {
overflow: hidden;
resize: auto;
padding: 15px;
border: 2px dashed #ccc;
}
<h2>Embedded Image</h2>
<div class="resize-demonstration">
<div class="container">
<h1>Title</h1>
<img src="https://placebear.com/g/200/100.jpg">
</div>
</div>

<h2>Background Image</h2>
<div class="resize-demonstration">
<div class="container bg-img" style="height: 300px">
<h1>Title</h1>
</div>
</div>

JSFiddle Demonstration

关于html - 如何使用 html 和 css 缩放(外部)元素与(内部)img 元素相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47767396/

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