如果我将文本粘贴到图像中,那么在本例中看起来不错。但如果我减小浏览器宽度,文本就会从图片中消失。
此外,添加了难看的换行符。
我怎样才能避免这两件事?
应该有没有滚动条的解决方案。
Long text is outside of the div
这是一个例子:https://jsfiddle.net/1228sbg7/3/
.image {
position: relative;
width: 33%;
height: auto;
}
h2 {
position: absolute;
top: 200px;
left: 0;
width: 100%;
}
h2 span {
color: white;
font: bold 24px/45px Helvetica, Sans-Serif;
letter-spacing: -1px;
background: rgb(0, 0, 0); /* fallback color */
background: rgba(0, 0, 0, 0.7);
padding: 10px;
}
h2 span.spacer {
padding:0 5px;
}
<div class="image">
<img src="https://www1.xup.in/exec/ximg.php?fid=21049048" alt="" />
<h2><span>Lorem ipsum dolor sit amet:<span class='spacer'></span><br /><span class='spacer'></span>consetetur sadipscing elitr</span></h2>
</div>
最佳答案
尝试将 overflow: hidden; 放在 < h2 > 元素的 CSS 定义中。
h2 {
position: absolute;
top: 200px;
left: 0;
width: 100%;
overflow: hidden;
}
此外,将您的 .image CSS 类定义替换为以下内容:
.image {
position: relative;
height: auto;
overflow-x:hidden;
}
根据您的评论进行的其他编辑:看起来您真的想要用文本填充黑暗区域。我进一步更改了您的 HTML,包装了 <h2>
div 周围的标签。而不是在 <h2>
中应用较暗的背景标签,我们在 <div>
上应用样式包装 <h2>
元素。
然后,使用 min-width 设置包装的最小宽度,以确保文本不会超出图像的高度。
body {
padding:0px;
margin:0px;
}
.image {
position: absolute;
width: 33%;
height: auto;
}
.darkerDiv {
background: rgb(0, 0, 0); /* fallback color */
background: rgba(0, 0, 0, 0.7);
padding: 5px 10px;
position: absolute;
top: 200px;
left: 0;
text-align:left;
min-width:170px !important;
overflow:hidden;
}
.darkerDiv h2 {
width: 100%;
margin: 0px;
padding: 0px;
}
.darkerDiv h2 span {
color: white;
font: bold 24px/45px Helvetica, Sans-Serif;
letter-spacing: -1px;
}
.darkerDiv h2 span.spacer {
padding: 0 5px;
}
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<link rel="stylesheet" href="StyleSheet2.css" />
</head>
<body>
<div class="image">
<img src="https://images.pexels.com/photos/301599/pexels-photo-301599.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=250&w=400" alt="" />
<div class="darkerDiv">
<h2><span>Lorem ipsum dolor sit amet: <br />
consetetur sadipscing elitr</span></h2>
</div>
</div>
</body>
</html>
关于html - 减小浏览器宽度时,文本在图像之外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50629777/