css - 嵌套div垂直对齐问题

标签 css vertical-alignment html

我正在尝试将一个 div(包含搜索栏)垂直居中放置在另一个(顶部横幅)中。我的印象是要这样做你做了以下事情:

#banner {
height: 35px;
width: 100%;
}

#searchbar {
    height: 15px;
    position: relative;
    top: 50%;
    margin-top: -7.5px; /* half of the height */
}

在您添加 margin-top 之前,这一切正常,此时它也应用于 #banner

是否有其他方法可以做到这一点,还是我只是做错了?

Here's a jsFiddle of my actual code.

最佳答案

我使用 line-height ,其值与父 div 的高度相同。

如下所示:http://jsfiddle.net/vkJ78/24/

CSS:

#banner    {
    background-color: #770E17;
    height: 35px;
    width: 100%;
    border-bottom: 1px solid #333;
    }

#src    {
    width: 300px;
    height: 15px;
    border: 1px solid #333;
    padding: 3px;
    }

#srcdiv {
    width: 308px;
    margin: 0px auto;
    position: relative;
    line-height: 35px;
}

编辑:根据 NGLN 的建议,这也将修复水平居中,#srcdiv#src 具有相同的宽度。

关于css - 嵌套div垂直对齐问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6863710/

相关文章:

css - Magento 1.9.2 中新产品 block 的奇怪样式

html - float 标题行

html - 使用 CSS 平衡表

html - 将跨度内的文本与容器顶部对齐

html - 如何在 html 和 css 旁边显示 2 个大按钮

jquery - 修复了 Twitter Bootstrap 中的导航栏导致隐藏部分的顶部内容

html - 如何在大于默认值的 <input> 内垂直对齐 Bootstrap 字形

css - 无法在嵌套结构中定义 div 的相对垂直位置

html - CSS HTML 如何让比div大的图片在div中完整显示

html - 播放一次动画而不是循环播放 three.js