给定以下 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
元素水平居中,不给它一个固定的宽度?下图显示了所需的结果:
到目前为止,这是我能得到的样子:
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/