![](/img/trans.png)
[英]Scale an image instead of wrapping text around it when the browser window is resized
[英]Text over image does not work when browser resized
背景
我需要在网站的图片上添加一些基本文字。首先使用rgb和rgba函数提供一个透明的黑框,然后将图片声明为“相对”,并将文字声明为“绝对”。
问题
调整浏览器大小时,文本在向下的方向上用完了图像。 它显示在https://jsfiddle.net/Lheg26kw/中,这是html-
<div class="hero-container">
<div class="hero-image">
<img src="https://upload.wikimedia.org/wikipedia/commons/0/05/Old-Style_Balinese_Cat.png" width=100% height=80%>
<div class="hero-text">
<p>This is text<br>
<span>this is some more text for trial of this problem</span></p>
</div>
</div>
</div>
这是CSS :
.hero-image{
position: relative;
width: 100%;
}
.hero-text p{
position: absolute;
text-align: center;
bottom: 0px;
top: 0px;
width: 100%;
background: rgb(0, 0, 0); /* fallback color */
background: rgba(0, 0, 0, 0.4);
padding-top: 80px;
color: white;
font-weight: bolder;
}
.hero-text span{
font-weight: normal;
}
需要
我需要将文本调整为最小大小后才能保留在图像上,即如果通过手机访问网站。
如果您没有在图像上放置最小尺寸,那么无论如何,最终文本都不适合。 但是我建议的一件事是更改您的padding-top: 80px;
从80px的恒定值到如padding-top: 25%;
的百分比padding-top: 25%;
。 随着图像尺寸的变化,这将有助于更好地缩放。
您可以将内容克隆到英雄下面的另一个div,然后隐藏。 hero-text
$(window).on('resize', function() { var $mobileContent = $('.mobile-content'); var $bodyWidth = $('body').width(); if ($bodyWidth < 620) { var $innerHero = $('.hero-text').html(); $mobileContent.html($innerHero); } else { $mobileContent.empty(); } }).trigger('resize');
body {margin: 0;} .hero-image { position: relative; width: 100%; } .hero-text p { position: absolute; text-align: center; bottom: 0px; top: 0px; width: 100%; background: rgb(0, 0, 0); /* fallback color */ background: rgba(0, 0, 0, 0.4); padding-top: 80px; color: white; font-weight: bolder; } .hero-text span { font-weight: normal; } .mobile-content { color: #000; font-weight: 700; text-align: center; } @media(max-width: 620px) { .hero-text { display: none; } }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <div class="hero-container"> <div class="hero-image"> <img src="https://upload.wikimedia.org/wikipedia/commons/0/05/Old-Style_Balinese_Cat.png" width=100% height=80%> <div class="hero-text"> <p>This is text <br> <span>this is some more text for trial of this problem</span> </p> </div> </div> </div> <div class="mobile-content"></div>
这将起作用:(用这些替换您的CSS)
.hero-image{
position: relative;
width: 100%;
}
.hero-image img{
width:100%;
display:block;
}
.hero-text{
width:100%;
height:100%;
background: rgb(0, 0, 0); /* fallback color */
background: rgba(0, 0, 0, 0.4);
position: absolute;
top:0;
left:0;
}
.hero-text p{
position: absolute;
text-align: center;
top: 50%;
transform:translateY(-50%);
-webkit-transform:translateY(-50%);
-moz-transform:translateY(-50%);
-ms-transform:translateY(-50%);
width:100%;
padding: 5px 0;
margin:0;
color: white;
font-weight: bolder;
}
.hero-text span{
font-weight: normal;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.