首页 > 解决方案 > How to position an element relative to a specific background image object?

问题描述

I have a background image with some objects like a company logo. This image is a full screen background and I want to align an element with the company logo and make it responsive.

I have searched for some similar solutions and tried using a solution proposed in this link: How to position an element relative to the background image width

Although I am able to position the element correctly, it doesn't remain in the same place relative to the image when the screen is resized.

How can I keep this html element always aligned?

body {
  width: 100%;
  height: 100%;
  background-image: url("http://www.rizwanashraf.com/wp-content/uploads/2008/11/mac-wallapers-13.jpg");
  background-size: cover;
  background-position: 0 0;
  background-repeat: no-repeat;
}

.container{
  position: relative;
}

.fixed-title{
  position: absolute;
  top: 0;
  margin: 28% 0 0 54%;
}
<div class="container">
  <h1 class="fixed-title">Apple</h1>
</div>

标签: htmlcss

解决方案


编辑:加上我在下面写的,这应该是你所追求的:) 剩下要做的就是改变百分比以匹配你所追求的位置。如果你需要在 px 中移动一些东西,你可以使用calc()css 函数来做

高度:计算(100% - 100px);

这将使你的东西 100% 的高度 - 100px。

body {
      width: 100%;
      height: 100%;
      position:relative
      background-image: url("http://www.rizwanashraf.com/wp-content/uploads/2008/11/mac-wallapers-13.jpg");
      background-size: cover;
      background-position: 0 0;
      background-repeat: no-repeat;
    }
.title-container{
      position: absolute;
      top: 50%;
      left:50%;
      transform: translate(-50%, -50%); 
    }
<body>
  <div class="title-container">
    <h1>My Title</h1>
  </div>
</body>

看起来您已经使用了一半postionion:absolute

我建议不要使用与and或速记版本结合margin:28% 0 0 54%使用的transform属性。translateX()translateY()translate( , );

下面的解决方案将您的标题放在容器的中心。

.fixed-title{
  position: absolute;
  top: 50%;
  left:50%;
  transform: translate(-50%, -50%); 
}

此解决方案仅将您的 h1 集中在 Y 轴上(上下)

.fixed-title{
  position: absolute;
  top: 50%;
  transform: translateY(-50%); 
}

此解决方案仅将您的 h1 集中在 X 轴(左右)

.fixed-title{
  position: absolute;
  left: 50%;
  transform: translateX(-50%); 
}

希望这会有所帮助:)

transformPs 这是一篇关于该物业所有用途的精彩文章的链接: https ://css-tricks.com/almanac/properties/t/transform/


推荐阅读