How can I place text on an elements border with transparency on the areas where text touches border?

Viewed 78

enter image description here

See the image above. I'd like to have the text on top of the border. How can I achieve this using html/css? Are there other alternatives

.wrapper {
  width: 100%;
  background: black;
  border: 4px solid purple;
  padding: 1rem;
  color: #FFF;
}

.wrapper p {
  text-align: center;
}

h1 {
  text-align: center;
}

a {
  display: table;
  margin: 0 auto;
  color: #FFF;
}
<div class="wrapper">
  <h1>
    Lorem ipsum dolor sit amet
  </h1>
  <p>
    Lorem ipsum
  </p>
  <a href="">Button</a>
</div>

3 Answers

You can achieve this using the pseudo elements of the h1 tag. In short, you have a wrapper div that creates the border left, right and bottom and still then use the pseudo elements of h1 to make the top border.

.wrapper {
  height: 100px;
  margin: 0 auto;
  width: 80%;
  margin-top: 30px;
  box-sizing: border-box;
  border: 5px solid tomato;
  border-top: none;
  position: relative;
}

.wrapper h1 {
  position: absolute;
  top: -41px;
  display: block;
  text-align: center;
  width: 100%;
  overflow: hidden;
  font-size: 2em;
}

h1:before,
h1:after {
  content: "";
  display: inline-block;
  width: 50%;
  margin-right:1em;
  margin-left:-50%;
  vertical-align: middle;
  border-bottom: 5px solid tomato;
}

h1:after {
  margin-right:-50%;
  margin-left:1em;
}

/*Demo Only*/

body{
background:url("https://i.imgur.com/fL3tbdj_d.webp?maxwidth=728&fidelity=grand") no-repeat;

background-size:100% 100%;
<div class="wrapper">
  <h1>
    TITLE HERE
  </h1>
</div>

<div class="wrapper">
  <h1>
    LONGER TITLE HERE
  </h1>
</div>

You can try to change the position of your h1 to relative, and move It

.wrapper p {
  position : relative;
  bottom : 30%;
 }

the bottom one means that It will move 30% to the top

Here is simple example may be it can give you an idea I found hard to edit your own codes so that's why I made this simple code

body {
  background-color: lightgreen;
}

.cont {
  height: 120px;
  width: 400px;
  border: 2px solid black;
  position: relative;
  margin: 40px
}

.cont:before {
  content: "My Header title";
  width: 180px;
  /* border: 1px solid; */
  position: absolute;
  text-align: center;
  top: -10px;
  background-color: lightgreen;
  left: 50%;
  transform: translateX(-50%);
}
<div class="cont"></div>

Related