带有标题的 Div 标签边框

tmp*_*dev 0 css border

我需要在 div 标签周围显示边框,边框本身带有标题。为了做到这一点,这是我到目前为止想出的

.componentWrapper {
  border: solid cadetblue;
  border-radius: 40px;
  padding: 10px;
  width: 95%;
}
    
.componentTitle {
  font-size: 18px;
  width: 15%;
  background-color: white;
  margin-top: -25px;
}
Run Code Online (Sandbox Code Playgroud)
 <div class='componentWraper'><p class='componentTitle'>This is the title</p>This is the component body text</div>
Run Code Online (Sandbox Code Playgroud)

如您所见,我正在使用边距属性将标题向上推到边框顶部。我不确定这是否是执行此操作的正确方法,我有以下问题。

  1. 我使用像素(边距)和固定值(-25px)定位标题。这是一个也必须在手机、平板电脑上运行的网站。这是一种可以接受的方法吗?
  2. 我将背景颜色设置为白色,这样边框就不会出现在文本后面,这是一个好的方法吗?
  3. 有没有更好,更可接受的方法来做到这一点,我不想使用字段集,因为我们对边界(边界半径)几乎没有控制。

Tan*_*sos 5

您可以使用三种合乎逻辑的方法来实现这一点。

  1. 您可以将 a<fieldset>与a一起使用,legend这是执行此操作的基本 HTML 方式。您可以在此处找到更多相关信息
  2. 使用带有定位的自定义 CSS,而不是负边距等:

body {
  background: #fff;
}

.componentWraper {
  margin: 40px; /* just for contrast */
  position: relative;
  border: 2px solid tomato;
  border-radius: 12px;
  padding: 20px;
}

.componentWraper .componentTitle {
  position: absolute;
  top: -25px;
  background: #fff;
  padding: 0 10px;
}
Run Code Online (Sandbox Code Playgroud)
<div class='componentWraper'>
  <p class='componentTitle'>This is the title</p>This is the component body text</div>
Run Code Online (Sandbox Code Playgroud)

  1. 使用带有伪元素的自定义 CSS :

body {
  background: #fff;
}

.componentWraper {
  margin: 40px; /* just for contrast */
  position: relative;
  border: 2px solid tomato;
  border-radius: 12px;
  padding: 20px;
}

.componentWraper::before {
  content: 'This is the title';
  position: absolute;
  top: -10px;
  padding: 0 10px;
  background: #fff;
}
Run Code Online (Sandbox Code Playgroud)
<div class='componentWraper'>This is the component body text</div>
Run Code Online (Sandbox Code Playgroud)