美文网首页
如何实现 label 文字右对齐,input左对齐

如何实现 label 文字右对齐,input左对齐

作者: 董懂同学 | 来源:发表于2017-04-15 17:11 被阅读5895次

在做百度前端技术学院 HTML/CSS作业的时候,遇到了这样的挑战。
在当时我还不知道要用labelinput前面的文字,所以用的表格布局,强行让其对齐。
后来在 stackoverflow 发现了这种解决方案 : 让label成为行内块元素,给其宽度,然后让文字居右即可。
HTML 代码如下

<form action="">
            <div class="block">
                <label for="username">用户名:</label>
                <input type="text" name="username">
            </div>
            <div class="block">
                <label for="password">密码:</label>
                <input type="password" name="password">
            </div>
            <div class="block">
                <label for="description">个人描述:</label>
                <textarea name="description" cols="30" rows="10"></textarea>
            </div>
            <div class="block center">
                <input type="submit" value="提交">
                <input type="reset" value="重置">
            </div>
</form>

CSS代码如下:

.block{
        width: 400px;
        display: block;
        margin:5px 0;
    }
.center{
        text-align: center;
}
label {
        display: inline-block;
        width: 100px;
        text-align: right;
}
input,textarea{
        vertical-align: top;
}

效果如图所示:

label文字右对齐,input左对齐效果

相关文章

网友评论

      本文标题:如何实现 label 文字右对齐,input左对齐

      本文链接:https://www.haomeiwen.com/subject/cctoattx.html