【问题标题】:Center a search bar in a container div that contains many other divs在包含许多其他 div 的容器 div 中居中搜索栏
【发布时间】:2012-12-23 05:05:21
【问题描述】:

我有一个容器 div,其中包含许多其他 div,并且在其中一个 div 中有一个搜索栏。因此 html 看起来像这样:

   <div id="header-middle">
        <div id="header-search">
            <form>
                <input type="text">
            </form>
        </div>
        <div id="header-middle-left">
        </div>
        <div id="header-transition">
        </div>
        <div id="header-middle-right">
        </div>
    </div>

我拥有的 CSS 是:

#header-middle{
    width: 400px;
    height: 64px;
    float: left;
}

#header-search{
    position: absolute;
    left: 50%;
    top: 50%;    
    margin-top: -32px;
    margin-left: -200px;
}

#header-middle-left{
    width: 241px;
    height: 64px;
    float: left;
    background-image:url('foo');
    background-repeat:repeat-x;
}

#header-transition{
    width: 19px;
    height: 64px;
    float:left;
    background-image:url('foo2');
}

#header-middle-right{
    width: 140px;
    height: 64px;
    float:left;
    background-image:url('foo3');
    background-repeat:repeat-x;
}

div 主要是为了样式而存在的,它们使用图像作为背景,因此覆盖它们的搜索栏没有任何害处。但是,我需要它以包含 div 为中心,并覆盖其余部分的一小部分。任何帮助将不胜感激。也将不胜感激有关一般 css 的任何建议。

【问题讨论】:

  • 我没有正确回答这个问题,但是你想要这样的东西吗:jsbin.com/icoyaz/1
  • 这正是您所需要的吗?我应该把它作为答案吗?
  • 是的,请!我会选择它作为答案。

标签: html css styles


【解决方案1】:

您应该编辑您的 CSS 来实现这一点,更改 #header-middle#header-search 以使用以下代码:

#header-middle {
    width: 400px;
    height: 64px;
    position: relative;
}

#header-search {
    position: absolute;
    left: 50%;
    top: 50%;    
    margin-top: -11px;
    margin-left: -75px;
    width: 150px;
    height: 22px;
}

这是DEMO

【讨论】:

  • 我不明白的一件事是为什么 -11px 和 -75px 而不是 -32 和 -200px?
  • 要将其置于中心位置,margin-left = width/2margin-top = height/2
  • 但是宽度是 400 所以如果它除以 2 就是 200 而 64/2 是 32 对吧?
  • #header-search : width = 150px, 所以margin-left = -75pxheight: 22px 所以margin-top: -11px
【解决方案2】:

您可以将position:relative 用于#header-search 使其位置相对于容器div #header-middle

如果搜索框和容器 div 的宽度和高度是静态的,则可以使用精确像素进行居中。这不是最好的方法,但它应该有效。如果它们是动态的,那么您可以使用 javascript 进行计算。

http://jsfiddle.net/rWNkj/

【讨论】:

  • 还是不行,那上面的红底是不是应该被完全遮住了?
猜你喜欢
  • 2015-04-18
  • 2021-10-20
  • 2013-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多