我试图水平中心一个<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将在中心。

.class-name {
    display:block;
    margin:0 auto;
}

其他回答

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

CSS代码:

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

最小宽度不是全局支持的,但是可以使用

.divclass {
   min-width: 200px;
}

然后可以将div设置为

<div class="center divclass">stuff in here</div>

问题的标题和内容实际上是不同的,所以我将发布两个解决方案,使用Flexbox。

我猜在IE8和IE9完全被摧毁之前,Flexbox将取代/添加到当前的标准解决方案中;)

检查当前flexbox的浏览器兼容性表

单一的元素

.container { 显示:flex; justify-content:中心; } < div class = "容器" > < img src = " http://placehold.it/100x100 " > < / div >

多个元素,但只以一个为中心

默认行为是flex-direction: row,将所有子项对齐在一行中。将其设置为flex-direction: column将有助于堆叠的行。

.container { display: flex; flex-direction: column; } .centered { align-self: center; } <div class="container"> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. </p> <div class="centered"><img src="http://placehold.it/100x100"></div> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. </p> </div>

margin: 0 auto;

正如ck所说,不是所有浏览器都支持min-width

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

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

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