gpt4 book ai didi

html - 将嵌套元素 w.r.t 定位到它的直接父元素

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

不确定我在这里弄错了什么,但假设我有两个 div 和一个 h1 元素(或 P1),看起来像这样:

<div class="wrapper">
<div class="top">
<h1>Content header</h1>
</div>
</div>

我希望我的元素出现在内部 div 的“中心中间”,即它的直接父级。为了实现这一点,我给它一个 margin-top:50% 和一个 margin-left:50% ,因为我知道这会将它精确地渲染到 div 的中心中间。但是,虽然它确实到达了中间,但并没有完全到达中心。事实上,它似乎相对于外部 div 定位自己,即带有类包装器的那个。

我在这里使用 jsfiddle 重新创建了这个:

http://jsfiddle.net/KLRsN/

是我指定的选择器有误还是我的定位本身不正确?

最佳答案

-上面的答案并不完全正确,因为文本仍然不会完全垂直居中。

.wrapper{
margin:5px;
max-height:250px;
min-height:250px;/*not required only height:250px will do*/
border:1px solid green;
}

.content
{
margin:5px;
border:1px solid black;
height:100px;/*you have to give the parent element a height and a width within which you wish to center*/
width:100px;
position:relative;/*giving it a position relative so that anything inside it will be positioned absolutely relative to this container*/
text-align:center;/*aligning the h1 to the center*/
}
.content h1{
border:1px solid black;
position:absolute;
top:50%;
left:50%;
line-height:50px;
width:50px;
margin-left:-25px;/*half the width of the h1 so that it exactly centers*/
margin-top:-25px;/*half the height of the h1 so that it exactly centers*/
}

解释:

-html 中的所有元素都是矩形框的形式,因此应用 margin-top:50% 是将该框的顶部与矩形框的 50% 对齐父元素而不是框内的文本。- 这就是文本未完全对齐中心的原因。

- 还必须为父元素(您希望将 h1 居中)提供宽度和高度。

正确的方法是使用绝对和相对定位。

-给 .container 一个相对的位置值,给 h1 一个绝对的值

-通过给 h1 一个宽度和高度,我们然后应用一个等于宽度一半的负左边距和一个等于高度一半的负上边距,以便文本完全居中。

  • 还有关于定位的更多信息 - 查看以下 link

关于html - 将嵌套元素 w.r.t 定位到它的直接父元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14211080/

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