html - 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>
解决方案
编辑:加上我在下面写的,这应该是你所追求的:) 剩下要做的就是改变百分比以匹配你所追求的位置。如果你需要在 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%);
}
希望这会有所帮助:)
transform
Ps 这是一篇关于该物业所有用途的精彩文章的链接: https ://css-tricks.com/almanac/properties/t/transform/
推荐阅读
- reactjs - SelectField 显示与值不同的字符串
- css - 将 px 转换为 rem 的 mixin 上的 Sass 弃用警告
- javascript - 使用 javascript 移动侧边栏菜单
- c++ - 如何获取从 C++ 发送到 Lua 函数的表的更新值?
- ios - iOS App Crash [UIKeyboardTaskQueue waitUntilAllTasksAreFinished] 仅在模拟器上
- asp.net - 我的 MS 访问更新一行
- sql-server - 使用过程从另一个表插入表
- ruby - Beaker Rspec 运行系统命令
- c++ - c++ 中不必要的包含
- github - 将 github 渲染的 .md 页面嵌入为 iframe