居中div不能与字体很棒一起正常工作

时间:2018-07-03 17:22:25

标签: html css center

问题:JSFiddle

我想将整个表单居中,并创建一个具有给定属性的名为“ center”的类。但是在将中心类添加到JSFiddle中的表单后,fontawesome图标保留在左侧,并且不会移动。它们应位于文本左侧输入元素的“内部”。因此,为了放置图标,我还在左侧添加了填充。

有人可以给我解决方案来解决由于居中而两个图标都位于左侧的问题吗?我真的不知道为什么它不起作用并且已经花费了很多时间:/

谢谢。

.center{
      text-align: center;
      margin-left: auto;
      margin-right: auto;
    }
    
    .box {
        position: relative;
        margin-bottom: 20px;
    }
    
    .box .fa {
        position: absolute;
        top: 10px;
        left: 5px;
    }
    
    .box input[type="text"],
    .box input[type="password"] {
        border: 0px;
        border-bottom: 1px solid #ccc;
        text-decoration: none;
        width: 180px;
        padding: 10px;
        padding-left: 25px;
    }
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

<div class="center">
<form action="/login" method="POST" class="form">
  <div class="box">
    <i class="fa fa-user" aria-hidden="true"></i>
    <input required name="username" type="text" placeholder="user">
  </div>
  <div class="box">
    <i class="fa fa-key" aria-hidden="true"></i>
    <input required name="password" type="password" placeholder="pass">
  </div>
  <div class="box">
    <input name="submit" type="submit" value="Login">
  </div>
</form>
</div>

2 个答案:

答案 0 :(得分:2)

.box元素是div,因此自然具有父元素的100%宽度。

一种简单的解决方案是为它们提供与您的input相同的固定宽度,并使用auto的左右边距将它们居中:

.center{
  text-align: center;
  margin-left: auto;
  margin-right: auto;
}

.box {
    position: relative;
    margin: 0 auto 20px;
    width: 180px;
}

.box .fa {
    position: absolute;
    top: 10px;
    left: 5px;
}

.box input[type="text"],
.box input[type="password"] {
    border: 0px;
    border-bottom: 1px solid #ccc;
    text-decoration: none;
    width: 180px;
    padding: 10px;
    padding-left: 25px;
}
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

<div class="center">
<form action="/login" method="POST" class="form">
  <div class="box">
    <i class="fa fa-user" aria-hidden="true"></i>
    <input required name="username" type="text" placeholder="user">
  </div>
  <div class="box">
    <i class="fa fa-key" aria-hidden="true"></i>
    <input required name="password" type="password" placeholder="pass">
  </div>
  <div class="box">
    <input name="submit" type="submit" value="Login">
  </div>
</form>
</div>

答案 1 :(得分:0)

它的发生是因为

.box .fa {
position: absolute;
top: 10px;
left: 5px;

}

您可以为其使用初始位置。