在 css 中,如何响应式地将元素粘贴到特定背景图像部分?
in css, how to responsively stick element to certain background image part?
并在调整大小时(即在不同设备中打开)时尽可能保持与背景图像相同的位置?
例如,有一个建筑物的背景图片,在它上面,需要创建一个悬停按钮,应该在它的左上角:
.bg
{
/* the background */
background-image: url(http://www.everbluetraining.com/sites/default/files/u47558/commercial-buildings.jpg);
background-size: cover;
background-repeat: no-repeat;
width: 100%
height:100%;
}
.mybtn
{
/* button image */
background-image: url(http://www.clipartbest.com/cliparts/dc8/ok9/dc8ok9nMi.png);
height: 30px;
width: 30px;
background-size: cover;
margin-top: 30px;
margin-left: 85px;
}
.mybtn:hover
{
opacity: 0.5;
}
<body class="bg">
<div class="mybtn"></div>
</body>
https://jsfiddle.net/saxzfoe2/
这在 720px 宽度下看起来不错,但是屏幕尺寸的任何变化都会使它超出所需的位置,在哪里挖掘?也许,媒体查询的一些帮助应该可以做到这一点?
(尝试使用 % 和 em 而不是 px 但仍然是相同的东西)
在 css 文件的顶部添加以下规则。
html, body{
height: 100%;
}
如果你想将按钮保留在位置的背景上,你想使用媒体查询 4 个断点。
在 css 上添加此代码:
html, body{
height: 100%;
}
并将 background-size : cover
编辑为 contain
。
.bg {
position : relative; // important
background-size : contain;
}
.myBtn{
position : absolute;
}
之后使用媒体查询,例如(这是一个示例!):
@media all and (min-width:720px) and (max-width: 767px){
.myBtn{
left : 10%;
top : 15%;
}
}
@media all and (min-width:768px) and (max-width:960px){
.myBtn{
left : 20%;
top : 15%;
}
}
在 Chrome 上找到你的断点。
并在调整大小时(即在不同设备中打开)时尽可能保持与背景图像相同的位置?
例如,有一个建筑物的背景图片,在它上面,需要创建一个悬停按钮,应该在它的左上角:
.bg
{
/* the background */
background-image: url(http://www.everbluetraining.com/sites/default/files/u47558/commercial-buildings.jpg);
background-size: cover;
background-repeat: no-repeat;
width: 100%
height:100%;
}
.mybtn
{
/* button image */
background-image: url(http://www.clipartbest.com/cliparts/dc8/ok9/dc8ok9nMi.png);
height: 30px;
width: 30px;
background-size: cover;
margin-top: 30px;
margin-left: 85px;
}
.mybtn:hover
{
opacity: 0.5;
}
<body class="bg">
<div class="mybtn"></div>
</body>
https://jsfiddle.net/saxzfoe2/
这在 720px 宽度下看起来不错,但是屏幕尺寸的任何变化都会使它超出所需的位置,在哪里挖掘?也许,媒体查询的一些帮助应该可以做到这一点?
(尝试使用 % 和 em 而不是 px 但仍然是相同的东西)
在 css 文件的顶部添加以下规则。
html, body{
height: 100%;
}
如果你想将按钮保留在位置的背景上,你想使用媒体查询 4 个断点。
在 css 上添加此代码:
html, body{
height: 100%;
}
并将 background-size : cover
编辑为 contain
。
.bg {
position : relative; // important
background-size : contain;
}
.myBtn{
position : absolute;
}
之后使用媒体查询,例如(这是一个示例!):
@media all and (min-width:720px) and (max-width: 767px){
.myBtn{
left : 10%;
top : 15%;
}
}
@media all and (min-width:768px) and (max-width:960px){
.myBtn{
left : 20%;
top : 15%;
}
}
在 Chrome 上找到你的断点。