我试图水平中心一个<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的情况下(即你不知道div将占用多少空间)。

#包装{ 背景颜色:绿色;/*用于可视化*/ text-align:中心; } # yourdiv { 背景颜色:红色;/*用于可视化*/ 显示:inline-block; } < div id = "包装" > <div id="yourdiv">你的文本</div> < / div >

请记住,#yourdiv的宽度是动态的->它将增长和缩小以适应其中的文本。

您可以在Caniuse上检查浏览器兼容性

其他回答

将这个类添加到您的css文件中,它将完美地工作 步骤:

1)先创造它

<div class="center-role-form">
  <!--your div (contrent) place here-->
</div>

2)添加到你的CSS

.center-role-form {
    width: fit-content;
    text-align: center;
    margin: 1em auto;
    display: table;
}

请使用下面的代码,您的div将在中心。

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

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

你可以在CSS上使用margin: 0 auto而不是margin-left: auto;margin-right:汽车;

如果你的<div>有position: absolute你需要使用width: 100%;

#parent {
    width: 100%;
    text-align: center;
}

    #child {
        display: inline-block;
    }