【问题标题】:How to position an element relative to the background image width如何相对于背景图像宽度定位元素
【发布时间】:2014-10-28 19:10:51
【问题描述】:

注意:我没有 JS 访问权限。这必须通过 CSS 完成。

我在屏幕右下角有一张背景图片 (850 x 1080)。我对图像进行了缩放,使其占据宽度的 38%:

background-position: right bottom;
background-size: 38% auto;
background-attachment: fixed;

现在我想定位另一个元素,使其始终与背景图像的某个部分对齐,无论屏幕大小如何。我该怎么做呢?我目前将它设置在距右侧和底部边缘一定距离的位置,但这不是我想要的:

height: 220px;
width: 155px;
bottom: 400px;
right: 400px;

My code can be found here,而我要定位的部分位于:hover + .hide 的定义中(第 12 行)。我正在尝试自定义的页面是我的MyAnimeList profile,我正在尝试将封面艺术与红色剑状事物的边缘对齐。

【问题讨论】:

标签: html css


【解决方案1】:

由于背景大小根据其容器的宽度而变化,您可以使用百分比边距来定位元素。 Percent Margins 根据容器的宽度计算,甚至是上/下边距 (see here)。

例子:

:hover + .hide{
    position:absolute;
    bottom:0;
    right:0;
    margin-bottom:20%; /* tune this */
    margin-right:20%; /* tune this */
}

这是一个DEMO

【讨论】:

  • 有没有办法让margin-bottom依赖margin-right,因为我将背景的高度设置为auto?
  • @Wyverncloak 正如我在回答中所说,边距底部和右边都是根据容器的宽度计算的,所以例如,如果您将它们都设置为 20% 它们将具有相同的值在px中根据父级宽度计算。
  • 我理解这一点,我的意思是如果我希望 margin-bottom 是任何 margin-right 以像素为单位的 1.2 倍。如果 margin-right: 20% 出来是 100px 对于那个屏幕,我想让 margin-bottom 120px。
  • @Wyverncloak 如果margin-right: 20%; 那么margin-bottom = 20% * 1.2 = 24%
  • 如果周围的容器是 800 x 1000,则结果为 160 x 240,而不是 160 x (160 * 1.2),即 160 x 192。
猜你喜欢
  • 1970-01-01
  • 2013-06-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-05
  • 2013-03-06
  • 1970-01-01
  • 2013-07-21
  • 2010-10-22
相关资源
最近更新 更多