如何在不更改内容并保持它们仍然左对齐的情况下使表单居中?

How do I center a form while not altering the contents and keeping them still aligned left?

提问人:azzyismeh 提问时间:11/14/2023 最后编辑:azzyismeh 更新时间:11/14/2023 访问量:35

问:

我在计算机科学课上的输入部分的最后一个问题要求我将其样式设置为现有网站的样式。这涉及使表单居中,而不是其内容。我有一个表单,其中包含一些输入标签和一个表格以及标题和 div。

我在这里查找了类似问题的解决方案,但没有一个适合我。

--- HTML ---
<body>
    <div id='main'>
        <form>
            <h1>Title</h1>
            <div>Subtitle</div>
            <section>
                <table>
                    --- Table Contents ---
                </table>
            </section>
            <section>
                --- Input Tags ---
            </section>
        </form>
    </div>
</body>
--- CSS ---
#main{
    display:inline-block;
    text-align:center;
    margin:0 auto;
}
form section{
    text-align:left;
    margin:8px;
    padding:10px;
}

这是我在尝试了其他帖子中的其他几种解决方案后现在所拥有的最一般的形式。发生的情况是,要么所有内容都向左对齐,要么除表格外的所有内容都居中,要么只有标题和 div 居中,但文本也是如此。

HTML CSS 对齐方式

评论


答:

0赞 orangecarnation 11/14/2023 #1

如果您还没有尝试 flexbox,我建议您尝试一下。就我个人而言,我并没有在带有文本的东西上使用它,但我总是发现它很有帮助,否则我很难让一些东西以我想要的方式居中。

用 a 将输入部分括起来,并给出具有这些属性的 CSS 类可能会解决问题:<div><div>

display: flex;
justify-content: center;

这应该将其中的所有元素水平居中(在本例中只是您的输入表单),但希望将文本保留在里面,因为这是一个具有自己属性的单独元素。

0赞 Brett Donald 11/14/2023 #2

一种可能的解决方案是将表单样式设置为内联块,这意味着它只会像容纳其内容所需的宽度一样宽。若要在页面上居中放置一个包装器,请在其周围放置一个带有样式的包装器,但随后请务必添加到表单本身,以防止表单内容居中。text-align: centertext-align: left

.form-wrapper {
  text-align: center;
}

form {
  display: inline-block;
  background: tan;
  padding: 0 2em;
  text-align: left;
  border-radius: 0.5em;
}
<div class="form-wrapper">
  <form>
    <h1>Title</h1>
    <p>I am some left aligned text</p>
    <p>Name <input type="text"></p>
    <p>Address <input type="text"></p>
    <p><input type="submit"></p>
  </form>
</div>

弹性框更简单:

.form-wrapper {
  display: flex;
  justify-content: center;
}

form {
  background: tan;
  padding: 0 2em;
  border-radius: 0.5em;
}
<div class="form-wrapper">
  <form>
    <h1>Title</h1>
    <p>I am some left aligned text</p>
    <p>Name <input type="text"></p>
    <p>Address <input type="text"></p>
    <p><input type="submit"></p>
  </form>
</div>