0

I know this is an old question, but I wanted to know what is the best way to put text into a border of a div tag. This is what I have

.componentWrapper {
  border: solid cadetblue;
  border-radius: 40px;
  padding: 10px;
  width: 95%;
}
<div class='componentWrapper'>Text inside div </div>

I want to add a title into the border of the div tag. I know one option is to use fieldsets but I prefer not to go with this approach. Another approach is the put a box and move it up and set the background color, but I think this fails when you set a different background color on the page.

What is the best solution for this?

Sumit patel
  • 3,807
  • 9
  • 34
  • 61
tmp dev
  • 8,043
  • 16
  • 53
  • 108
  • I started with an inner `span` and pseudo elements ... after 20 min. I stopped, as this will be an insane pixel matching to make that work, so you have 2 (reasonable) options, `fieldset` or use a SVG for border/text ... for cross browser support I recommend `fieldset`, as I can't see **any** reason not to, not even what one want/prefer is a reason good enough, simply use the elements as they are meant to be used, or you will end up with invalid code every where – Asons Mar 07 '17 at 07:52
  • but this is not a form, that is why I want to avoid using fieldset. – tmp dev Mar 07 '17 at 10:30
  • Its valid without: http://stackoverflow.com/questions/9812898/is-it-wrong-to-use-the-fieldset-tag-without-form-tag – Asons Mar 07 '17 at 15:35

1 Answers1

6

I would suggest something like that, using position:absolute:

.componentWrapper {
  border: solid cadetblue;
  border-radius: 40px;
  padding: 15px 10px 10px;
  width: 95%;
}

.componentWrapper .header {
  position:absolute;
  margin-top:-25px;
  margin-left:10px;
  color:white;
  background:cadetblue;
  border-radius:10px;
  padding:2px 10px;
}
<div class='componentWrapper'><div class="header">Headline</div>Text inside div </div>
Psi
  • 6,387
  • 3
  • 16
  • 26