gpt4 book ai didi

css - 相对于父级 100% 宽度的绝对位置元素

转载 作者:行者123 更新时间:2023-11-28 16:39:20 25 4
gpt4 key购买 nike

我正在尝试将元素绝对定位在设置为 position: relative 的父元素中,到目前为止一切顺利。

问题是,父元素的宽度为 100%,当 right:0 时,绝对定位元素将一直固定在浏览器的右侧。

我真正想要的是正确定位元素,使其与宽度为 1140 像素的页面包装对齐。

如果我设置权限为fx。 100px的absolute元素,当然在不同的分辨率下会有不同的结果。

有点难以解释,所以我做了一个 jsFiddle: https://jsfiddle.net/wxxezx0w/1/

.navigation {
width:500px;
background:#def;
margin:0 auto;
text-align:center;
padding:5px 0;
margin-bottom:10px;
}
.navigation ul {
list-style-type:none;
padding:0;
}
.navigation ul li {
display:inline;
padding-right:20px;
}
.grandParent {
position:relative;
width:100%;
}
.parent {
background: url('http://dummyimage.com/1800x1200/ccc/ccc') no-repeat 0 20%;
background-size:cover;
height:300px;
}
.child h1 {
position: absolute;
top: 25%;
left: 25%;
color: #fff;
font-size: 60px;
font-weight: bold;
width: 50%;
text-align: center;
}
.child .box {
position: absolute;
bottom: -10px;
right: 0;
background: #fed;
padding: 10px 25px;
color: #000;
font-size: 20px;
z-index: 10;
display: block;
}
<div class="navigation">
<ul>
<li>
Home
</li>
<li>
Page1
</li>
<li>
Page2
</li>
</ul>
</div>
<div class="grandParent">
<div class="parent">
<div class="child">
<h1>Hello world</h1>
<div class="box">Align me right, relative to navigation div</div>
</div>
</div>
</div>

最佳答案

试试这个:

.navigation {
width:500px;
background:#def;
margin:0 auto;
text-align:center;
padding:5px 0;
margin-bottom:10px;
}
.navigation ul {
list-style-type:none;
padding:0;
}
.navigation ul li {
display:inline;
padding-right:20px;
}
.grandParent {
position:relative;
width:100%;
}
.parent {
background: url('http://dummyimage.com/1800x1200/ccc/ccc') no-repeat 0 20%;
background-size:cover;
height:300px;
}
.child h1 {
position: absolute;
top: 25%;
left: 25%;
color: #fff;
font-size: 60px;
font-weight: bold;
width: 50%;
text-align: center;
}
.child < .box {
position: absolute;
bottom: -10px;
right: 0;
background: #fed;
padding: 10px 25px;
color: #000;
font-size: 20px;
z-index: 10;
display: block;
}

请注意,我已经在您的 CSS 中更改了 parent 关系,添加了 >这意味着第一个 child ,例如:。 child < .box {}

如果你在 CSS 中设置一个标签和另一个标签之间的空格意味着第一个包含第二个,在这种情况下是正确的,但也存在亲子关系。

这里是 jsfiddle:https://jsfiddle.net/wxxezx0w/2/

关于css - 相对于父级 100% 宽度的绝对位置元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33953326/

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