我需要在 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)
如您所见,我正在使用边距属性将标题向上推到边框顶部。我不确定这是否是执行此操作的正确方法,我有以下问题。
您可以使用三种合乎逻辑的方法来实现这一点。
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)
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)