我正在开展一个网页项目,我在屏幕中央有一张图片。在那张照片的顶部,我在一个盒子里有一些文字。当屏幕是全宽时,我“几乎”拥有它想要的大小。但是,当我缩小屏幕时,文本会移动到整个地方。
我有以下代码:
.imageFit {
padding-top: 5%;
width: 100%;
height: 100%;
}
.imageText span {
position: absolute;
top: 75%;
left: 40%;
padding: 10px;
text-align:center;
color: white;
background: rgba(0,0,0,0.7);
letter-spacing: -1px;
}
<div class="container">
<img class="imageFit" src="https://hd.unsplash.com/photo-1420593248178-d88870618ca0">
<div class="container">
<h1 class="imageText "><span>Begins with one step</span></h1>
</div>
</div>
提示:如果需要更多信息,请与我们联系。
答案 0 :(得分:2)
你走了。我删除了一些不必要的标签,并使您的文字响应。
.imageFit {
padding-top: 5%;
width: 100%;
height: 100%;
}
.imageText {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
padding: 10px;
text-align:center;
color: white;
background: rgba(0,0,0,0.7);
letter-spacing: -1px;
font-size: 4vw;
}
.container {
position: relative;
}
<div class="container">
<img class="imageFit" src="https://pixabay.com/static/uploads/photo/2016/01/12/19/16/painting-1136443_960_720.jpg">
<h1 class="imageText ">Begins with one step</h1>
</div>
答案 1 :(得分:1)
如果你想保留所有css,你可以取出<h1>
标签,然后只使用内容:before
选择器:
https://jsfiddle.net/ukdt27oz/1/
<div class="container">
<img class="imageFit" src="https://hd.unsplash.com/photo-1420593248178-d88870618ca0">
</div>
.imageFit {
padding-top: 5%;
width: 100%;
height: 100%;
}
.container:before {
content: "Begins with one step";
color: black;
position: absolute;
top: 50%;
left: 35%;
padding: 10px;
text-align:center;
color: white;
background: rgba(0,0,0,0.7);
letter-spacing: -1px;
font-size: 5vw;
}
答案 2 :(得分:1)
将绝对定位的元素以您期望的方式转移到DOM上总是很棘手。
import java.text.MessageFormat;
import java.util.Scanner;
/*4. Rectangles
Write an expression that calculates rectangle’s perimeter and area by given width and height.*/
public class Rectangles {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Please enter width:");
double width = scan.nextDouble();
System.out.print("Please enter height:");
double height = scan.nextDouble();
double area = 2 * width + 2* height;
double perimeter = width*height;
System.out.println(MessageFormat.format("Perimeter {0}",perimeter));
System.out.println(MessageFormat.format("The rectangle's area is {0}", area));
}
}
定位元素从自然文档流中取出,它们与围绕它们移动的其他元素无关。
我们可以通过在给定的父元素上声明absolute
来控制它。现在,这将相对于此父级定位。
position: relative;
.imageFit {
width: 100%;
height: 100%;
}
.imageText span {
position: absolute;
left: 0;
right: 0;
max-width: 50%;
width: 100%;
display: block;
margin: auto;
top: 0;
bottom: 0;
box-sizing: border-box;
max-height: 65px;
padding: 10px;
text-align:center;
color: white;
background: rgba(0,0,0,0.7);
letter-spacing: -1px;
}
.container-wrapper {
position: relative;
}