skip to Main Content

I need to do something like this in css, how to achieve it (look attachment)?

attachment:

Do I need to use after, before to do something like this or can I do it using only border to do this? Can someone help me with this

Regards

3

Answers


  1. This might help get you started:

    • Create a <div> with a border
    • Create a <span> with a white background
    • Move the span so that it sits "over" the top of the border
    .border{
        border: 3px solid black;
        width: 50vw;
        height: 50vh;
    }
    
    .text{
        display: inline-block;
        text-align:center;
        position: relative;
        top: -0.6rem;
        left: 50%;
        padding: 0 0.5rem;
        transform: translateX(-50%);
        background-color: white;
    }
    <div class="border">
        <span class="text">SOME TEXT</span>
    </div>
    • In this case I have used position: relative
    • You could also use absolute position if the parent div is also positioned in the document, or the div is already at the top left of the document
    • For more about positioning see MDN docs position
    Login or Signup to reply.
    1. Create a wrapper div, and set border.
    2. Create a title div inside the wrapper div with background color of white.

    You can set the wrapper div position relative. As for the title div, set the position to absolute with left, and right values.

    Here’s the code example.

    .wrapper {
      border: 1px solid;
      border-radius: 10px;
      position: relative;
      margin: 2rem;
      max-width: 400px;
      width: 100%;
      padding: 1rem;
    }
    
    .title {
      font-size: 1.5rem;
      font-weight: 600;
      background-color: white;
      position: absolute;
      left: 50%;
      top: -1rem;
      transform: translateX(-50%);
      padding: 0 1rem;
    }
    <div class="wrapper">
      <div class="title">
        My Heading
      </div>
    
      <div>
        <p>
          my description text
        </p>
      </div>
    </div>
    Login or Signup to reply.
  2. A straightforward solution is to embed the HTML that goes in the square in a <fieldset> and use <legend> for the text over the border. Optionally with &nbsp; before and after the <legend> text for extra spacing.

    fieldset { border-radius: 15px }
    
    legend {
        text-transform: uppercase; /* [OPTIONAL] */
        margin: 0 auto;            /* [OPTIONAL], to center the LEGEND */
    }
    <fieldset>
        <legend>&nbsp;legend&nbsp;</legend>
        <p>Some &lt;p&gt; with text.</p>
        <div>Some &lt;div&gt; with text.</div>
    </fieldset>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search