html - 如果右侧的 div 上有内容,则在左侧居中的 div

标签 html css

我有一个居中的 div,另一个在右侧,可能有一些内容。如果右边的这个有内容,居中的需要向左移动。最后,两个 div 的内容需要居中。

例如:我在中心有一个搜索框。如果我有搜索结果 - 结果和搜索框需要位于中心。所以搜索框向左移动了一点。

我怎样才能用 CSS 制作它?

最佳答案

一种方法是使用 text-align: centerdisplay: inline-block。这是一个以两个元素为中心的 fiddle :http://jsfiddle.net/rs6bmfq9/ .而且,这里有一个略有不同的 fiddle ,其中删除了“文本”div:http://jsfiddle.net/hrham7w9/ .

HTML:

<div class = "container">
    <input type = "text" />
    <div>
        Nam at justo dignissim, dapibus lorem eget, consectetur metus. Suspendisse vitae massa a nunc congue pulvinar non luctus mi. Nam turpis ex, laoreet tempor justo ac, cursus convallis urna. Sed eros ligula, congue ut lacinia auctor, porttitor ut quam. Nullam maximus, dui in eleifend viverra, est augue vestibulum est, id lacinia nibh ante vel velit. Aenean vitae sem ipsum. In porta felis urna, vel tincidunt odio aliquam feugiat.
    </div>
</div>

CSS:

.container {
    white-space: nowrap;
    text-align: center;
}

.container > * {
    display: inline-block;
}

.container > input {
    width: 30%;
    vertical-align: top;
}

.container > div {
    width: 40%;
    text-align: left;
    white-space: normal;
    vertical-align: top;
    border: 1px dotted gray;
}

关于html - 如果右侧的 div 上有内容,则在左侧居中的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26819170/

相关文章:

css - 带有 Twitter Bootstrap 问题的响应式 CSS

html - 不使用绝对定位设置图层高度

jquery - 搜索功能无法选择的文本

css - 使用 HTML5/CSS 向图像添加文本

html - 如何使用 Ant 在 JMeter 测试中附加结果 HTML 输出文件

font-family 的 CSS 变量是 "invalid property"即使变量外的相同字符串很好

c# - 在线设计名片应该使用pixel还是cm?

html - Bootstrap 3 旋转木马上的居中按钮

html - 普通网站如何开启https协议(protocol)?

html - 使 <div> 的背景颜色填充封闭的 <td>