首页 > 解决方案 > 在输入下对齐错误消息 - HTML/CSS

问题描述

我有以下图像代表用户输入验证的每种情况。

无错误:

在此处输入图像描述

输入错误:

在此处输入图像描述

我想在输入字段下方移动错误消息时保持上图的对齐(保持标签在左侧,输入在右侧,将错误消息放在下方并与输入对齐)。

.group {
  display: flex;
  flex-wrap: nowrap;
  margin-top: 4px;
}

.group label {
  display: flex;
  width: 15%;
  line-height: 30px;
  justify-content: center;
  align-items: center;
}

.group input[type="text"] {
  width: 85%;
  border: 1px solid rgb(116, 115, 115);
  padding-left: 3px;
}

.group textarea:focus,
input:focus {
  outline: none;
}

.group .errorMsg {
  color: #cc0033;
  display: inline-block;
  font-size: 12px;
  line-height: 15px;
  margin: 5px 0 0;
  width: 100%;
}

.group .errorMsg {
  display: none;
}


/* Error Styling */

.err label {
  color: #cc0033;
}

.err input[type=text] {
  background-color: #fce4e4;
  border: 1px solid #cc0033;
  outline: none;
}

.err .errorMsg {
  display: inline-block;
}
<div class="group err">
  <label for="time">Time</label>
  <input type="text" name="time" id="time" />
  <div class="errorMsg">Invalid Time Format</div>
</div>
<div class="group">
  <label for="time2">Time2</label>
  <input type="text" name="time2" id="time2" />
  <div class="errorMsg">Invalid Time Format</div>
</div>

有什么建议可以解决对齐不良的问题吗?

标签: htmlcss

解决方案


你可以像这样对齐它们。我在更改的右侧添加了注释。

.group {
  display: flex;
  flex-wrap: wrap; /* Wrap the elements */
  margin-top: 4px;
}

.group label {
  display: flex;
  width: 15%;
  line-height: 30px;
  justify-content: center;
  align-items: center;
}

.group input[type="text"] {
  width: 85%;
  border: 1px solid rgb(116, 115, 115);
  padding-left: 3px;
  flex: 1; /* Take the remaining width */
}

.group textarea:focus,
input:focus {
  outline: none;
}

.group .errorMsg {
  color: #cc0033;
  display: inline-block;
  font-size: 12px;
  line-height: 15px;
  margin: 5px 0 0;
  width: 100%;
}

.group .errorMsg {
  display: none;
}


/* Error Styling */

.err label {
  color: #cc0033;
}

.err input[type=text] {
  background-color: #fce4e4;
  border: 1px solid #cc0033;
  outline: none;
}

.err .errorMsg {
  display: flex; /* Instead of inline-block */
  width: 85%; /* Same as input width */
  left: 15%; /* Rest of the width */
  position: relative; /* Relative to parent */
  
}
<div class="group err">
  <label for="time">Time</label>
  <input type="text" name="time" id="time" />
  <div class="errorMsg">Invalid Time Format</div>
</div>
<div class="group">
  <label for="time2">Time2</label>
  <input type="text" name="time2" id="time2" />
  <div class="errorMsg">Invalid Time Format</div>
</div>


推荐阅读