我需要在 div 背景上有一个图像。在这张图片上,必须有一个标题、副标题和一个按钮。
所有这三个元素都需要在 % 中有 top 和 left 以获得动态位置。
我试过几次,但都没有成功。
HTML
<div id="container">
<div id="block1">
<div id="title">LIAM</div>
<div id="subtitle">SUPER SLIM FIT</div>
<div id="link">
<a href="#"> See all jeans</a>
</div>
</div>
</div>
CSS
#block1 {
background-image: url('http://tiffosi.com/fw16/img/img1.jpg');
background-repeat: no-repeat;
background-size: contain;
width: 100%;
height: 1450px;
max-width: 1086px;
max-height: 1450px;
position: relative;
top: 0;
left: 0;
}
#block1 #subtitle {
font-size: 16pt;
color: white;
position: absolute;
top: 23.4%;
left: 43.5%;
letter-spacing: 1px;
}
#block1 #link {
width: 184px;
text-align: center;
height: 43px;
line-height: 43px;
border: 1px solid white;
font-size: 11pt;
top: 29.3%;
left: 41.3%;
position: absolute;
}
#block1 #link a {
color: white;
text-decoration: none;
font-weight: 100;
}
@media only screen and (min-width : 768px) {
#block1 #title{
top: 12%;
left:42%;
font-size:80%;
}
}
@media only screen and (min-width : 992px) {
#block1 #title {
font-size: 100%;
position: absolute;
top: 16.5%;
left: 42%;
letter-spacing: 2px;
}
}
#block1 #title {
font-size: 97px;
color: white;
position: absolute;
top: 16.5%;
left: 42%;
letter-spacing: 2px;
}
jsffidle 链接:https://jsfiddle.net/jggscada/
最佳答案
与其单独定位每个元素,我建议您将 position:absolute
赋予 #block1
并将其定位在图像上(图像作为背景 #container
或在 #block1
div 周围创建另一个 div ) 。
我使用了 top:40vh
-> vh=viewport height
然后根据需要将元素放置在 block1
中。
我还删除了 #link
div 并将样式直接添加到链接。这样看起来更合乎逻辑:)。如果你想要一个 link
表现得像一个 div
使用 display:block
,在这种情况下我使用 display:inline-block
非常重要:如果您希望某些内容具有响应性,请不要使用固定的 width
和 height
。我在 .container
上使用了 width:100vw
,因此它具有屏幕的宽度。
请参阅下面的片段或在此处 fiddle > Jsfiddle
让我知道它是否适合你
#container {
background-image: url('http://tiffosi.com/fw16/img/img1.jpg');
background-repeat: no-repeat;
background-size: contain;
width: 100vw;
height: 1450px;
max-width: 1086px;
max-height: 1450px;
position: relative;
top: 0;
left: 0;
border: 1px solid red;
}
#block1 #title {
font-family: oswald-bold;
font-size: 60pt;
color: white;
letter-spacing: 5px;
}
#block1 #subtitle {
font-family: oswald-bold;
font-size: 16pt;
color: white;
letter-spacing: 1px;
}
#block1 a{
width: 184px;
text-align: center;
height: 43px;
line-height: 43px;
border: 1px solid white;
font-family: Oswald-Medium;
font-size: 11pt;
color: white;
text-decoration: none;
font-weight: 100;
display:inline-block;
margin-top:50px;
}
#block1 {
position:absolute;
top:40vh;
left:0;
margin:0 auto;
right:0;
text-align:center;
}
<div id="container">
<div id="block1">
<div id="title">LIAM</div>
<div id="subtitle">SUPER SLIM FIT</div>
<a href="#"> See all jeans</a>
</div>
</div>
关于CSS 位置 div 在背景图像上的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39081645/