You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现登录标题嵌入边框且不被边框线条遮挡?

解决方案:用fieldset和legend实现标题嵌入边框效果

直接用<fieldset>和<legend>标签就能完美解决你的需求,这两个标签是HTML原生用来实现带标题的表单容器的,不需要复杂的定位或背景覆盖技巧。

修改后的HTML结构

把原来的容器div.form-container替换成fieldset.login-container,并将<h1>Sign in</h1>换成<legend>Sign in</legend>,同时修正class名和结构对应:

<body>
<fieldset class="login-container">
  <legend>Sign in</legend>
  <form>
    <div class="form-input">
      <input type="text" name="username" placeholder="Username" required>
    </div>
    <div class="form-input">
      <input type="password" placeholder="Password" required>
    </div>
    <button type="submit" class="login-btn">Log in</button>
    <p class="text">Don't have an account? <a href="CreateAcc.html">Create an Account</a>
      <a href="CreateAcc.html">Forgot Password?</a></p>
  </form>
</fieldset>
</body>

调整后的CSS样式

移除原来针对h1的绝对定位和负margin,给legend设置样式,同时调整fieldset的默认样式:

.login-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400px;
  width: 300px;

  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);

  border: 1px solid rgba(255,255,255,0.1);
  border-radius: 10px;
  padding: 2rem 1rem; /* 调整内边距,给表单留出空间 */
  background: inherit; /* 继承背景,让legend的背景和容器一致 */
}

.login-container legend {
  font-family: 'DM Sans', serif;
  color: #fff;
  font-size: 2.2rem;
  padding: 0 1rem; /* 给标题左右加内边距,让边框和标题之间有空隙 */
  background: inherit; /* 关键:设置背景和容器一致,遮挡后面的边框 */
}

/* 保留你原来的按钮样式 */
.sign-in-btn,
.create-account-btn{
  color: white;
  padding: 10px 20px;
  margin: 10px;
  border-radius: 5px;
  font-size: 16px;
  width: 200px;

  box-shadow: inset 0 0 0 0 #1db954;
  transition: ease-out 0.3s;
  background: none;
  border: #1db954 solid 1px;
  position: relative;
  z-index: 1;
}
.sign-in-btn:hover,.create-account-btn:hover{
  color: #FFFFFF;
  background: #1db954;
}
.sign-in-btn:before,.create-account-btn:before{
  transition: 0.5s all ease;
  position: absolute;
  top: 0;
  left: 50%;
  right: 50%;
  bottom: 0;
  opacity: 0;
  content: "";
  background-color: #1db954;
}
.sign-in-btn:hover:before,.create-account-btn:hover:before {
  transition: 0.5s all ease;
  left: 0;
  right: 0;
  opacity: 1;
  z-index: -1;
}

关键说明

  • <legend>会自动让<fieldset>的边框在标题位置断开,不需要额外处理边框遮挡
  • 给legend设置background: inherit是为了让标题的背景和容器一致,避免容器背景透明时边框透过标题显示
  • 调整fieldset的padding是因为它默认有内边距,需要适配你的布局

内容的提问来源于stack exchange,提问作者Kels

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 20:15:50