为什么表单的所有元素都不正确对齐?



我不明白为什么我的表单的所有元素都不遵循align="right"标签。理想情况下,我希望所有内容都居中,但我注意到,用于键入问题、添加金钱和添加标记的部分留在左侧,而用于添加文件和提交按钮的部分是唯一遵循<form>标记对齐规则的元素。为什么会这样?如何将所有对齐在一起?

    <div class="container">
        <!--Sections: Question, Add money, Add file, Submit-->
        <form role="form" align="right">
        <!-- Section to type question-->
            <div class="form-group" id="AddQuestion">
                <textarea class="form-control" rows="5" placeholder="Search"></textarea>
            </div>
        <!--Section to add money---->
            <div class="input-group" id="AddMoney">
              <span class="input-group-addon">$</span>
              <input id="EnterMoney" type="text" class="form-control" onkeypress='validate(event)'>
            </div>
        <!--Section to add tags-->
            <div class="input-group" id="AddTag">
              <input type="text" class="form-control" placeholder="Tags" aria-describedby="basic-addon1">
            </div>
        <!--Section to add file-->
            <div id="AddFile">
                <a href="#" onclick="document.getElementById('uploadFile').click(); return false;" />Add File</a>
                <input type="file" id="uploadFile" style="visibility: hidden;" />
            </div>
            <div id="imagePreview"></div>
        <!--Section for the Submit button-->
            <div>
                <button type="submit" class="btn btn-primary">Submit</button>
            </div>
        </form>
    </div>
</body> 
CSS

form {
}
.container {
    max-width:500px;
}
#imagePreview {
    width: 100px;
    height: 100px;
    background-position: center center;
    background-size: cover;   
    display: inline-block;
}
#AddMoney {
    max-width:200px;
}
#AddFile {
    position:relative;
    top:20px;
}
#AddTag {
    position:relative;
    top:20px;
}

这是因为在你的控件上应用了其他CSS类。例如,divtextarea的CSS类分别为form-groupform-control。检查你的CSS,你就能看到是哪个CSS类导致了这个问题。

您可以使用F12按钮打开浏览器的开发工具,当您检查元素时,它会显示相应的HTML和CSS。

HTML的align属性随着HTML5和CSS3的发布而过时。一个很好的解决方法是使用CSS属性来使用margin-left或margin-right属性对齐元素。

#example {
margin-left: 1px; /*play around with these values*/
margin-right 1px; /*play around with these values*/
}

使用这些值,它们应该会得到你需要的。如果你愿意,你也可以使用百分比值来设置左距和右距。

最新更新