首页 > 解决方案 > 使用背景图像和顶部图像无法正常工作

问题描述

我试图创建一个个人资料页面,我网站的用户将有一个图像作为一种横幅,然后是个人资料照片。

我已经能够做到这一点:

在此处输入图像描述

当我尝试top-margin在图像上使用时,它会移动图像但也会扩展图像的背景,我不想要这个。我希望得到这个:

在此处输入图像描述

我注意到在我的代码中,图像似乎是重复的,而不是仅仅适合/裁剪。

下面是代码:

class Profiles extends React.Component{

    render(){
        return(
            <div className="profile-container">
                <div className="profile-header" 
                    style={{ backgroundImage: `url(${UserProfile.User1.values.profileHeaderImag})`}}>
                        <img 
                        src={UserProfile.User1.values.profileImg} 
                        alt="profileImg"
                        className="profile-header-image-user"/>                    
                </div>
                <div className="profile-content">
                    <p> more</p>
                </div>
            </div>
        )
    }   
}

和CSS

.profile-container {
        margin-top: 3rem;
        margin-bottom:5rem;

}

.profile-header {
    width: 70% ;
    height: 5% ;
    max-height: 25rem;
    margin-left: auto;
    margin-right: auto;
    background-color: blue;
    border-radius: 20px;
}


.profile-header-image-user {
    border-radius: 150px;
    width: 130px;
    height: 130px;
    margin-left: 5%;
    margin-top: 15%;
}

.profile-content {
    width: 60%;
    background-color: green;
    margin-left: auto;
    margin-right: auto;
}

我的目标是能够显示横幅和个人资料图片,如第二张图片所示,并在屏幕尺寸更改时保持此渲染。

有什么想法可以移动个人资料图片并影响横幅的大小吗?

谢谢

标签: javascripthtmlcssreactjsreact-bootstrap

解决方案


您需要将您的父position:relative元素和子元素(个人资料图片)设为position:absolute. 然后你可以设置top left rightbottom。我使用了翻译,虽然你也可以使用bottom:-50px; box-sizing:border-box,但认为变换在这里是一个更好的选择

.banner {
  position: relative;
  height: 200px;
  width: 100%;
  background: url("https://i.imgur.com/T8YRjiQ.jpeg");
  background-size: 100% 100%;
  margin-bottom: 55px;
  border-radius: 10px;
  box-shadow: 5px 5px 10px #222;
  border: 5px solid silver;
  box-sizing: border-box;
}

.profile {
  position: absolute;
  height: 156px;
  width: 156px;
  border: 5px solid silver;
  border-radius: 50%;
  bottom: 0;
  left: 50px;
  transform: translateY(50%);
  box-shadow: inherit;
}
<div class="banner">

  <img class="profile" src="https://i.imgur.com/LxxvbbL.png" />

</div>


推荐阅读