我试图水平中心一个<div>块元素在页面上,并将其设置为最小宽度。最简单的方法是什么?我想要<div>元素内联与我的页面的其余部分。我来举个例子:

page text page text page text page text
page text page text page text page text
               -------
               | div |
               -------
page text page text page text page text
page text page text page text page text

当前回答

在大多数浏览器,这将工作:

div.centre { 宽度:200 px; 显示:块; background - color: # eee; margin-left:汽车; margin-right:汽车; } <div class=" center ">一些文本</div>

在IE6中,你需要添加另一个外部div:

div.layout { text-align:中心; } div.centre { text-align:左; 宽度:200 px; background - color: # eee; 显示:块; margin-left:汽车; margin-right:汽车; } < div class = "布局”> <div class=" center ">一些文本</div> < / div >

其他回答

CSS, HTML: Div.mydiv{宽度:200px;Margin: 0 auto} < div class = " mydiv”> 我在中间 < / div >

您的图表还显示了块级元素(通常是div),而不是内联元素。

在我的头顶,在FF2+/Safari3+/IE7+中支持min-width。可以在IE6上使用巧妙的CSS,或者简单的JS。

.center { 高度:20 px; 背景颜色:蓝色; } .center > div { 保证金:汽车; 背景颜色:绿色; 宽度:200 px; } < div class = "中心" > < / div > < div >你文本 < / div >

小提琴

对这个问题最好的回答是使用margin-auto,但要使用它,你必须知道你的div的宽度在px或%。

CSS代码:

div{
    width:30%;
    margin-left:auto;
    margin-right:auto;
}

这里我添加了正确的答案

您可以使用此片段代码并进行自定义。这里我使用2个子块。这应该显示页面的中心。 您可以使用一个或多个块。

<html>
<head>
<style>
#parent {
    width: 100%;
    border: solid 1px #aaa;
    text-align: center;
    font-size: 20px;
    letter-spacing: 35px;
    white-space: nowrap;
    line-height: 12px;
    overflow: hidden;
}

.child {
    width: 100px;
    height: 100px;
    border: solid 1px #ccc;
    display: inline-block;
    vertical-align: middle;
}
</style>
</head>

<body>

<div class="mydiv" id="parent">


<div class="child">
Block 1
</div>
<div class="child">
Block 2
</div>

</div>
</body>
</html>

你应该在父元素上使用position: relative和text-align: center,然后在你想居中的子元素上使用display: inline-block。这是一个简单的CSS设计模式,适用于所有主流浏览器。下面是一个示例或查看CodePen示例。

p { text-align: left; } .container { position: relative; display: block; text-align: center; } /* Style your object */ .object { padding: 10px; color: #ffffff; background-color: #556270; } .centerthis { display: inline-block; } <div class="container"> <p>Aeroplanigera Mi Psychopathologia Subdistinctio Chirographum Intuor Sons Superbiloquentia Os Sors Sesquiseptimus Municipatio Archipresbyteratus O Conclusio Compedagogius An Maius Septentrionarius Plas Inproportionabilit Constantinopolis Particularisticus.</p> <span class="object centerthis">Something Centered</span> <p>Aeroplanigera Mi Psychopathologia Subdistinctio Chirographum Intuor Sons Superbiloquentia Os Sors Sesquiseptimus Municipatio Archipresbyteratus O Conclusio Compedagogius.</p> </div>