html - 当另一个元素 float 在它旁边时,如何水平居中(居中)一个未知宽度的元素?

标签 html css centering

给定以下 HTML:

<div id="container">
    <div id="left">Left</div>
    <div id="centre">Centred</div>
</div>

和 CSS:

#left {
    float: left;
    text-align: left;
}

#centre {
    text-align: center;
}

如何centre 元素水平居中,给它一个固定的宽度?下图显示了所需的结果:

The "left" element is on the left side. The "centred" element is centred horizontally relative to the container. Both elements are vertically aligned.

到目前为止,这是我能得到的样子:

The "left" element is on the left side. The "centred" element is centred horizontally relative to the space between the right side of the "left" element and the right side of the container. Both elements are vertically aligned.

Here's a jsFiddle demonstrating what I have done so far.

我更喜欢不需要指定任何宽度的通用解决方案。

最佳答案

如果你知道左边div的宽度,你可以这样做:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">

<style media="all">

#left {
    float: left;
    width: 30px;
}

#centre {
    margin: 0 40px;
    text-align: center;
}

#left, #centre, #container {
    border: 1px solid #000;
}

#container {
    width: 175px;
    padding: 5px;
}

</style>

</head>
<body>

<div id="container">
    <div id="left">Left</div>
    <div id="centre">Centred</div>
</div>

</body>
</html>

关于html - 当另一个元素 float 在它旁边时,如何水平居中(居中)一个未知宽度的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16781929/

相关文章:

html - 如何在媒体查询设置的流体布局中垂直和水平居中子元素?

html - 如何在 float 按钮元素之间垂直和水平居中文本?

jquery - 是否有可能在按钮上有一个图像 (.png) 并且仍然能够单击该按钮

HTML 将主要元素分配给一个 id

javascript - 如何将我的 Onclick 和 Onmouseover 从我的 HTML 移动到我的 javascript?

html - 在列表元素内的(链接)标签内垂直对齐跨度

javascript - 使用 jQuery 更改图像

javascript - 根据价格过滤

javascript - 当内容为 "injected"时,jQuery 模态窗口不居中

javascript - 如何在ul下拉菜单中显示选定的菜单项