内联块和边距:自动不适用于输入

问题描述 投票:0回答:6

我是CSS的新手。我希望我的文本框(输入)居中对齐,我也想设置一个特定的高度。我希望它能够响应,所以我使用的是%而不是px。它(%)似乎适用于宽度,但不适用于高度。对于高度,只有px值有效。另外,我将输入的显示属性指定为inline-blockmargin 0 auto,但它不起作用。我哪里错了?

这是代码:

input {
    width: 70%;
    margin: 0 auto;
    display: inline-block;
    height: 20%;
}

这是一个代码示例。

input {
    width: 70%;
    margin: 0 auto;
    display: inline-block;
    height: 20%;
}
<input type="text">
html css css3
6个回答
2
投票

如果你想使用%作为高度,你必须首先添加一些帮助CSS。如下:

html,body{
  height:100%;
}

并使<input>中心使用

margin: 0 auto;
display: block;

适合您的工作样本:

input {
  width: 70%;
  margin: 0 auto;
  display: block;
  height: 20%;
}

html,
body {
  height: 100%;
}
<input type="text">

有一个简单的方法,如果你有兴趣,你可以使用vh [视口高度],对于这种方法,没有必要使用任何其他帮助CSS使用,所以选择你的..

此方法的工作示例:

input {
    width: 70%;
    margin: 0 auto;
    display: block;
    height: 20vh;
}
<input type="text">

希望这有用。


1
投票

在CSS中,元素的一些(如果不是大多数)属性取决于其父元素的属性。

因此,要使height: 20%工作,您需要为input的父级设置高度。在下面的例子中,bodyinput的父母。

要使用margin: 0 auto对元素进行居中对齐,元素必须具有display: block

html, body {
  height: 100%;      /* Set a parent height */
}
input {
    width: 70%;
    margin: 0 auto;
    display: block;  /* Use display: block; */
    height: 20%;
}
<input type="text">

0
投票

将此样式设置为input标记。

input {
    width: 70%;
    margin: 0 auto;
    display: block;
    height: 20vh;
}
<input type="text">

0
投票

你需要给显示:块对齐中心输入和显示:内联块已经在这里应用并给身高,html用于高度输入

html,body{
  height:100%;
}
input {
    width: 70%;
    margin: 0 auto;
    display: block;
    height: 20%;
}
<input type="text">

0
投票

如果你不使用flex那么display:block;width对于居中元素很重要。

div {
    width: 100%;
    display: block;
}

input{
  display:block;
  width: 70%;
  padding: 5px;
  font-size:18px;
  margin:0 auto;
}
<div>
  <input type="text">
</div>

0
投票

display: inline-block;改为display: block;height: 20%;改为height: 20vh;

input {
    width: 70%;
    margin: 0 auto;
    display: block;
    height: 20vh;
}
<input type="text">

UPDATE

只将display: inline-block;改为display: flex;

input {
    width: 70%;
    margin: 0 auto;
    display: flex;
    height: 20%;
}
<input type="text">
© www.soinside.com 2019 - 2024. All rights reserved.