我将此代码用于多篇文章并且我认为它工作正常,除非我尝试通过添加样式 position: relative
和 id="target"
但随后图像宽度缩小为 0 或者它们消失了,我不知道我在这里犯了什么样的错误。请指教。
尝试删除 position: relative
和 id="target"
并查看代码如何工作。
即使有使用 jQuery 或 JS 实现该概念的更好方法,也请分享。
.article {
border: 1px solid red;
padding: 0;
display: flex;
}
.article-content {
border: 1px solid black;
width: 46.66%;
text-align: left;
align-self: center;
margin-left: auto;
}
.img-control {
border:1px solid black;
max-width: 53.66%;
margin-right: auto;
margin-left: 1rem;
overflow: hidden;
}
.image {
width: auto;
width:100%;
}
.img-control img {
display: block;
max-width: 100%;
width: auto;
}
img #target {
transform: scale(2.2) translate(-35%, 29%) rotate(-25deg);
width: 670px;
display: block;
position: absolute;
}
@media only screen and (max-width:480px) {
.article {
flex-flow: wrap column;
}
.article-content, .img-control {
margin: 0 auto;
}
}
<div class="article">
<div class="article-content">
<h3 class="mainTitle">What is Lorem Ipsum?</h3>
<h5 class="subTitle">Lorem Ipsum</h5>
<p> is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.</p>
</div>
<div class="img-control" style="position: relative;">
<div class="image">
<img src="http://via.placeholder.com/466x585" width="100%" alt="" style="width: 670px;right: -48px;top: -18px; display: block;position: absolute;" id="target" />
</div>
</div>
</div>
最佳答案
如果您想使用绝对定位,您需要让父容器具有 position:absolute 或 position:relative。
此外,为了让一个元素占据其父元素的整个高度或宽度,您需要设置父元素的高度/宽度,然后将子元素的高度/宽度设置为 100%(父元素中的所有可用空间)。最初您将图像高度设置为 670,因此它超出了父元素 block Per Mdn
Percentages refer to the width of the containing block
<style>
.article {
border: 1px solid red;
padding: 0;
display: flex;
}
.article-content {
border: 1px solid black;
width: 46.66%;
text-align: left;
align-self: center;
margin-left: auto;
}
.img-control {
border:1px solid black;
width: 20.66%;
height:156px;
margin-right: auto;
margin-left: 1rem;
overflow: hidden;
}
.image {
height:100%;
width:100%;
}
.img-control img {
display: block;
height:100%;
width:100%;
}
img#target {
transform: scale(2.2) translate(-35%, 29%) rotate(-25deg);
width: 670px;
display: block;
position: absolute;
}
@media only screen and (max-width:480px) {
.article {
flex-flow: wrap column;
}
.article-content, .img-control {
margin: 0 auto;
}
}
</style>
</head>
<body>
<div class="article">
<div class="article-content">
<h3 class="mainTitle">What is Lorem Ipsum?</h3>
<h5 class="subTitle">Lorem Ipsum</h5>
<p> is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.</p>
</div>
<div class="img-control" style="position: relative;">
<div class="image">
<img src="http://via.placeholder.com/466x585" width="100%" alt="" style="top: -18px; display: block;position: absolute;" id="target" />
</div>
</div>
</div>
关于javascript - 使用相对位置和绝对位置时,我的图像消失了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48350101/