计算机科学课程中输入部分的最后一个问题要求我将其设计为现有网站的风格。这涉及到以形式为中心,但不以内容为中心。我有一个表单,其中包含一些输入标签和一个表格,以及一个标题和 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 居中,但文本也居中。
如果您还没有尝试过,我建议您尝试一下 Flexbox。我个人并没有在带有文本的事物上使用它太多,但当我很难让某些东西按照我想要的方式居中时,我总是发现它很有帮助。
用
<div>
包围输入部分,并为其提供 <div>
具有这些属性的 CSS 类可能会达到目的:
display: flex;
justify-content: center;
这应该将其中的所有元素水平居中(在本例中只是您的输入表单),但希望将文本保留在其中,因为这是一个具有自己属性的单独元素。
基本思想是将表单设计为内联块,这意味着它的宽度只会达到容纳其内容所需的宽度。要将其在页面上居中,请在其周围放置一个 wrapper,并使用
text-align: center
样式,但请务必将 text-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>