【问题标题】:CSS - how to render buttons on top of a background image?CSS - 如何在背景图像上呈现按钮?
【发布时间】:2020-08-06 07:05:27
【问题描述】:

你好堆栈溢出,

我目前正在构建一个具有背景图像的组件,并且在这个背景图像上,我想在背景图像的某个部分上精确呈现按钮。我的意图是使这个可调整大小 - 尽管纵横比,按钮应该保持在某个区域上。

这是标准布局的样子:https://imgur.com/a/IzKLUI7

如果我使用纵横比,这就是它的样子:https://imgur.com/a/TqZkAsA

编辑:这是一个代码框的链接,其中包含我正在使用的最新设计的再现:https://codesandbox.io/s/keen-rgb-do24t

当我调整页面的纵横比时,是否有可能在背景图像的特定区域上仍然有这些按钮?如果我调整窗口大小,我注意到按钮会飞离背景图像。我在下面附上了我的代码。

应用:

import React, { Component } from 'react';
import './Home.css'

class Home extends Component    {
    render()    {
        return (
           <div className="container">
                <div className="box-one">
                    <button className="button"> Image One </button>
                    <button className="button2"> Image Two </button>
                </div>
           </div>
        );
    }
}
 
export default Home;

CSS:

.container {
  background-image: url(../components/space_wallpaper.png);
  background-repeat: no-repeat;
  background-size: cover;
  position: relative;
  left: 10vw;
  top: 10vh;
  height: 80vh;
  width: 80vw;
  outline: 1px solid blue;
}

.box-one {
  outline: 1px solid red;
  display: flex;
}

.button {
  position: absolute;
  margin: 1% 1%;
}

.button2  {
  position: absolute;
  margin: 50% 50%;
}

【问题讨论】:

  • 尝试背景尺寸:封面;
  • 嗨Chandradeepta,我试过了,我发现当我调整大小时,我在底部的任何按钮都会消失/离开背景图像。我可以使用封面,但我必须确保按钮不会离开容器组件。
  • 我已经在下面回答了。请看一看。如果你想要一些具体的东西,请告诉我。
  • 最好(如果这个答案不是你想要的),发布一个代码框来测试它。
  • @Apostolos,听起来不错。这是一个代码框的链接 - codesandbox.io/s/keen-rgb-do24t

标签: javascript css reactjs button background-image


【解决方案1】:

这就是你要找的吗?

.container {
  background-image: url(../components/space_wallpaper.png);
  background-repeat: no-repeat;
  background-size: cover;
  position: relative;
  left: 10vw;
  top: 10vh;
  height: 80vh;
  width: 80vw;
  outline: 1px solid blue;
}

.box-one {
  outline: 1px solid red;
  display: flex;
}

【讨论】:

  • 嘿Chandradeepta,这不是我想要的,但我相信它更接近最终目标。我认为有一个作为封面的背景尺寸是好的。我现在正在做的是在我的每个按钮中,我将它们的位置设置为绝对位置。我正在将您对 CSS 的演绎版用于 box-one。我现在遇到的问题是,如果底部有任何按钮,并且如果我缩小页面,这些按钮将离开我的组件。查看此 Imgur 链接:imgur.com/a/WKidvLm 和此代码框链接:codesandbox.io/s/keen-rgb-do24t
  • 不要使用绝对位置。相反,将容器用作 flexbox,将按钮用作 flex 项。所以你可以随心所欲地控制他们的行为
  • Chandradeepta,感谢您的帮助!我想知道是否可以按照您的方式在特定位置映射多个按钮。例如,如何将“图片二”按钮放置在第一个按钮(图片一)的右侧约 10 像素处?
  • 在 .box-one 类中删除 justify-content 属性。并将 .button2 样式添加为 .button2 { align-self: center;边距顶部:10px; } codesandbox.io/s/stupefied-babbage-iyp6c?file=/src/…
猜你喜欢
  • 2013-08-10
  • 2022-10-04
  • 2020-01-15
  • 1970-01-01
  • 2015-10-07
  • 2013-01-31
  • 1970-01-01
  • 1970-01-01
  • 2011-09-19
相关资源
最近更新 更多