gpt4 book ai didi

html - 如何相对于CSS中的其他元素有选择地定位元素

转载 作者:太空宇宙 更新时间:2023-11-04 13:05:57 24 4
gpt4 key购买 nike

您好,我想知道如何使用 CSS 相对于其他元素专门对齐/定位 html 元素。这是一把 fiddle http://bit.ly/1tbOHEY我希望在其中显示侧边栏元素 1 以与具有 id="alignwithme1" 的 div 对齐侧边栏元素 2 与具有 id="alignwithme2" 的 div 对齐,这将导致类似于下图的结果。 enter image description here

是否可以使用 CSS 对其他 html 元素进行选择性定位?解决方案将非常有帮助。提前谢谢了。 :)

最佳答案

事情是这样的。 CSS 选择器不能向后遍历。因此,无法单独使用 css 对两个独立元素的子元素设置相对样式,除非其中一个元素是另一个元素的子元素。

如果您想要一个完整的 CSS 方法并且 #usual1 的高度未知,这可能是您唯一的选择:

HTML

<div id='header'>Header</div>
<div id="mainpost">
<div id="alignwithme1">Align with Me 1
<div id="se1">Sidebar element 1</div>
</div>
<div id="usual1"></div>
<div id="alignwithme2">Align with Me 2
<div id="se2">sidebar element 2</div>
</div>
</div>

& CSS

#header{width:auto; height:25px; font-size:15px; text-align:center;background:black; color:white;}
#mainpost{width:50%; height:auto; background:yellow; color:black;padding:12px;float:left;}
#usual1{width:160px;height:145px;background:black;color:white;margin:10px;}
#alignwithme1{width:auto; height:50px;background:black;color:white;margin:10px;text-align:center;padding:4px;}
#alignwithme2{width:auto; height:50px;background:black;color:white;margin:10px;text-align:center;padding:4px;}
#sidebar{width:40%; height:auto;float:right;}
#se1{width:auto;height:35px;color:black;background:#44accf;padding:9px;text-align:center;margin:10px;}
#se2{width:auto;height:35px;color:black;background: #44accf;padding:9px;text-align:center;margin:10px;}

#alignwithme1,
#alignwithme2{
position: relative;
}
#se1,
#se2{
width: 80%;
position: absolute;
top: -10px;
left: 110%;
}

这是用于在垂直菜单中定位子菜单的方法。

否则,您将不得不使用 JS 找出顶部偏移量并使用它来定位您的元素。希望这会有所帮助。

关于html - 如何相对于CSS中的其他元素有选择地定位元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25130598/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com