尝试使用CSS纵向和横向居中子元素

时间:2013-04-22 19:10:37

标签: html css centering

我如何能够在父级方面纵向和横向地使用子元素。

#bigBanner  {
position: relative;
width: 960px;
height: 483px;
margin: 0 auto;
background-image:url(../wpimages/sliderbg.jpg);
}

#bannerQuote    {
width: 518px;
height: 127px;
margin: 0 auto;
background-color: #0d0f11;
opacity: 0.95;
filter:Alpha(opacity=95);
}

是否代码,bannerQuote正好位于bigBanner的中间。我怎么做到这一点?我觉得这很简单。

由于

2 个答案:

答案 0 :(得分:1)

你可以做点像......

#bannerQuote {
  position:absolute;
  top: 50%;
  left: 50%;
  margin-left: -259px;
  margin-top: -64px;
  width: 518px;
  height: 127px;
  background-color: #0d0f11;
  opacity: .95;
  filter:Alpha(opacity=95);
}

其中margin-left和margin-top由您的身高和宽度决定。由于您将左上角设置为父容器的中心,因此您需要将子元素的一半宽度调回到左侧,将其一半高度调回顶部。

答案 1 :(得分:0)

只要您在具有特定高度和宽度的父元素中有一个具有特定高度和宽度的子项,您就可以将子项从顶部和左侧绝对定位。 像:

#bannerQuote    {
 position:absolute;
 top: 178px;
 left: 221px;
 width: 518px;
 height: 127px;
 margin: 0 auto;
 background-color: #0d0f11;
 opacity: 0.95;
 filter:Alpha(opacity=95);
}

如果您想在具有动态值的父级中定位具有已知高度和宽度的子项,请参阅fletchs answer。