【问题标题】:Relatively Positioning two elements to a fixed div将两个元素相对定位到一个固定的 div
【发布时间】:2020-05-04 19:52:43
【问题描述】:

我正在尝试将我的“.store”类放置在我的#linkplaceholder div 上方 10 像素处,并将我的“.lastseen”类放置在我的 #linkplaceholder div 下方 10 像素处。这可能吗?

我想这可以通过绝对位置和相对位置来完成,但是当我将 #linkplaceholder 更改为位置:绝对时,它不再像应有的那样水平居中。此外,#linkplaceholdering div 的大小需要在视口的 20% 处保持动态。

目前我只是通过给 store 一个上边距百分比和 lastseen 下边距百分比来定位 '.store' 和 '.lastseen' 类,以便你看到我想要的想法。这些有时位于它们需要的一般区域,但在不同的设备上它们可能会很远。这就是为什么我需要将 store 准确定位在上方 10px 并且最后一次看到定位在准确定位下方 10px 的原因,因此这是固定的并且始终准确。

JSFiddle 显示我的代码:https://jsfiddle.net/1ms9fk63/

    body {
        background: black;
    }
    #container {
	    background-color: black;
	    z-index: 0;
		position: fixed;
		left: 0;
		right: 0;
		top: 0;
		bottom: 0;
		width: 100%;
		height: 100%;
	}
	#linkplaceholder {
		margin: 0 auto;
		z-index: 10000000;
		position: fixed;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		width: 20%;
	}
	#linkplaceholder img {
		width: 100%;
	}
	.store {
		top: 0;
		margin-top: 21.5%;
	}
	.lastseen {
		bottom: 0;
		margin-bottom: 21.5%;
	}
	.lastseen, .store {
		position: absolute;
		width: 100%;
		text-align: center;
	}
	.lastseen a, .store a {
		font-family: neue-haas-grotesk-text, sans-serif;
		color: #ffffff;
		font-weight: 400;
		font-style: normal;
		list-style: none;
		text-align: center;
		text-decoration: none;
		font-size: 15px;
	}
	.lastseen a:hover, .store a:hover {
		text-decoration: underline;
	}
      <div id="container">
        <div id="linkplaceholder">
          <a href="/">
            <img src="images/image.svg" alt="" />
          </a>
        </div>
        <div id="navcontainer">
          <div class="store"><a href="/store">STORE</a></div>
          <div class="lastseen"><a href="/last-seen">LAST SEEN</a></div>
        </div>
      </div>

【问题讨论】:

    标签: html css position


    【解决方案1】:

    我建议使用JavaScript,因为我认为仅使用CSS 无法完成类似的事情。查看我创建的thissn-p。

    注意:我必须使用 div 顶部的 20px,因为如果我使用 10px,文本会进入图像内部。

    【讨论】:

    • 酷,谢谢!如果即使在调整视口大小后链接仍然能够正确定位,则此路线可以工作。我注意到它们在调整大小后保持不变。此外,我注意到与“STORE”和图像相比,“LAST SEEN”和图像之间在视觉上看起来有更多的空间。你知道这是为什么吗?行高问题?
    • 您可以使用setInterval() 每隔n 秒重复一次相同的脚本,或者如果视口发生变化,您可以刷新网页。我认为链接和图片之间的可变空间量是由于图片未对齐,因为我认为它适用于文本而不是 img。
    • 你认为这样的事情 (w3schools.com/jquery/event_resize.asp) 可以以某种方式实现而不是重复脚本吗?并射击!我确信我的 img 完全对齐。你知道我哪里出错了吗?
    • @JohnSmith 我创建了另一个 sn-p:jsfiddle.net/sfjc1oL2/1。似乎有一个未知的修饰符,因为如果我不将lastseen 元素向下移动10px,它仍然是图片下方的20px
    • @JohnSmith 你也可以试试这个:jsfiddle.net/sfjc1oL2/2 我根据img 元素定位元素,我认为这就是你想要的(我不需要从中减去任何东西元素)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-29
    • 1970-01-01
    相关资源
    最近更新 更多