【发布时间】:2020-05-28 02:01:26
【问题描述】:
我想在页面上居中放置一个表单,我已经做到了。不过,我有一个问题:当我调整浏览器窗口的大小并且高度减小时,我希望表单保持在导航栏下方并且页面溢出并允许我滚动,以便查看表单的其余部分。相反,它将自己定位在导航栏上方。
我尝试将表单包含在另一个容器 div 中,尝试使用不同的位置值,但我没有成功获得我想要的。有没有简单的方法?
#navbar {
background-color: blue;
width: 100%;
height: 50px;
border: 1px solid black;
}
.test_form {
/* Center the form on the page vertically */
margin: 0 auto;
/* Center both vertically and horizontally */
position: absolute;
top: 50%;
left: 50%;
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
/* Center both vertically and horizontally */
min-width: 400px;
width: 28vw;
max-width: 550px;
/* Form outline */
padding: 1em;
border: 2px solid #192D4D;
border-radius: 2em;
}
@media only screen and (max-height: 500px) {
.test_form {
/* Center the form on the page vertically */
margin: 0 auto;
min-width: 400px;
width: 28vw;
max-width: 550px;
/* Form outline */
padding: 1em;
border: 2px solid #192D4D;
border-radius: 2em;
/* Just to know when it switches */
background-color: red;
}
}
label {
/* Uniform size & alignment */
display: inline-block;
width: 100px;
text-align: center;
}
input,
textarea {
/* To make sure that all text fields have the same font settings
By default, textareas have a monospace font */
font: 1em sans-serif;
/* Uniform text field size */
width: 100%;
box-sizing: border-box;
/* Match form field borders */
border: 1px solid #999;
background-color: #F1F9FF;
}
textarea {
/* Align multiline text fields with their labels */
vertical-align: top;
}
table {
width: 100%;
border-collapse: collapse;
border: 2px solid #192D4D;
letter-spacing: 1px;
font-size: 0, 8rem;
text-align: center;
background-color: #ADBEDA;
}
td,
th {
border: 1px solid #5C6F8C;
padding: 5px 10px;
text-align: left;
}
.submit-button {
margin-left: calc(1em + 2vw);
min-width: 100px;
width: 8vw;
max-width: 150px;
}
<div id='navbar'>
</div>
<br>
<form class="test_form">
<table border="1">
<thead>
<tr>
<th colspan="2" scope="row">Table form</th>
</tr>
</thead>
<tr>
<th>asdasd</th>
<td>asdad</td>
</tr>
<tr>
<th>asdasd</th>
<td><input value='asda'></td>
</tr>
<tr>
<th>asdasd</th>
<td>asdad</td>
</tr>
<tr>
<th>asdasd</th>
<td><textarea>asdads</textarea></td>
</tr>
</table>
<br>
<input class="submit-button" type="submit" value="Submit" />
</form>
@media 下方的 CSS 是我之前使用的代码,它只将表单水平居中,但它在垂直位置方面具有所需的行为(保持在导航栏下方和溢出)。
【问题讨论】:
-
不要使用表格进行布局。看看flexbox
标签: css position media-queries centering