0

不知道我在这里做错了什么,但假设我有两个 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/

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

4

2 回答 2

1

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

.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*/
}

解释:

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

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

做你正在寻找的正确方法是使用绝对和相对定位。

- 给出相对的.container位置值和h1绝对的值

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

  • 还可以了解更多关于定位的信息 - 查看以下链接
于 2013-01-08T11:19:07.957 回答
0

如果要在中间显示文本内容,可以使用 text-align:center ,或者可以将宽度应用于 h1 标签并使用 margin:auto。要将其垂直放置在中间,请使用相对位置和 top:50% 。试试这个 CSS

.wrapper{
   height:250px;
   min-height:250px;
   border:1px solid green;
  }

 .content{
  position:relative;
  top:50%;
   border:1px solid black;
 }
 .content h1{
   border:1px solid blue;
   margin:auto;
   width:100px;
   background:red
 }

希望能帮助到你

于 2013-01-08T09:20:25.467 回答