如何将HTML <FORM> 显示为内联元素?

93

这可能是一个基本的HTML/CSS问题...

我有一个简单的单按钮表单,我想在段落文本中将其显示为内联。

<p>Read this sentence 
     <form style='display:inline;'>
     <input style='display:inline;' 
            type='submit' 
            value='or push this button'/>
     </form>.
</p>

即使表单有style=display:inline属性,我仍然在表单前面得到了一个换行符。有没有办法摆脱它?

表单元素可以出现在<p>中吗?


3
感谢所有人的答案和评论! - Evgeny
7个回答

80

将表单标签移到段落外,将边距/内边距设置为零:

<form style="margin: 0; padding: 0;">
  <p>
    Read this sentence 
    <input style="display: inline;" type="submit" value="or push this button" />
  </p>
</form>

3
我的表单中的外边距和内边距没有生效,我不得不使用display:inline代替,这样外边距和内边距就不再必要了。 - angularsen
2
"display:inline" 对我也起了作用。为什么不在你的答案中添加到表单样式呢? - Praesagus

58

<form>不能放在<p>标签内。当浏览器尝试处理没有关闭的段落元素时,它会在遇到开放的<form>标签时突然关闭您的<p>元素:

<p>Read this sentence 
 </p><form style='display:inline;'>

23

你可以尝试这段代码:

<form action="#" method="get" id="login" style=" display:inline!important;">

  <label for='User'>User:</label> 
  <input type='text' name='User' id='User'>

  <label for='password'>Password:</label><input type='password' name='password' id='password'>
  <input type="submit" name="log" id="log" class="botton" value="Login" />

</form> 

需要注意的重要事情是在 <form> 标签中的 css 样式属性。

display:inline!important;


6
根据HTML规范<form><p>都是块级元素,不能嵌套。也许用<span>替换<p>对你有帮助?
编辑: 抱歉,我的措辞太仓促了。正如HTML规范中的段落所指定的那样,<p>元素不允许包含任何块级内容。

3
有些块级元素可以嵌套(例如 div 元素),但有些是特殊的,不应该嵌套。例如,段落标签只能包含内联元素。 - Zack The Human

2
添加内联包装器。
<div style='display:flex'>
<form>
 <p>Read this sentence</p>
 <input type='submit' value='or push this button' />
</form>
<div>
    <p>Message here</p>
</div>

你没有关闭第一个div。 - Daniel Katz

0

我认为你可以通过将提交按钮包含在段落中来实现你想要的效果:

     <pre>
     <p>Read this sentence  <input  type='submit' value='or push this button'/></p>
     </pre>   

0

只需以以下方式使用样式float: left

<p style="float: left"> Lorem Ipsum </p> 
<form style="float: left">
   <input  type='submit'/>
</form>
<p style="float: left"> Lorem Ipsum </p>

3
与其使用“float”技巧,不如像其他答案中建议的那样修复标记。 - Jeremy J Starcher

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接