Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rectangular shape behind text in CSS

Tags:

html

css

I'm trying to make a very simple design in CSS. I have a title and a paragraph. I need to add a rectangle behind it, so that the text overflows this rectangle.

Something like this : https://i.sstatic.net/L95Wr.png

I tried many different things, one solution I made is :

<div class="container">
  <div class="rectangle">

  </div>
  <div class="main">
    <h1>
      This is the title
    </h1>
    <p>This is a paragraph paragraphparagraphpararrrrrgrapaaaaaaaaaah.</p>
  </div>

</div>
.container {
  text-align: center;
  left: 0;
  right: 0;
 }

.rectangle {
  position: relative;
  width: 180px;
  height: 140px;
  margin: auto;
  z-index: -1;
  border: 5px solid lightgray;
}

.main {
  width: 300px;
  min-height: 60px;
  margin: auto;
  margin-top: -150px;
}

https://jsfiddle.net/bcsg6q03/3/

But I need a better solution. This one relies on margin-top: -150px; So everything moves if I change the text or the rectangle size.

Is there's a better way to do so ? Thanks

like image 873
Remi Avatar asked Sep 10 '26 08:09

Remi


1 Answers

Using :before and left

.container {
  text-align: center;
  left: 0;
  right: 0;
 }

.main {
  position:relative;
  width: 300px;
  min-height: 60px;
  margin: auto;
  padding-top:15px;
}

.main:before {
  content:'';
  position: absolute;
  width: 220px;
  height: 140px;
  margin: auto;
  z-index: -1;
  border: 5px solid lightgray;
  left:40px;
}
<div class="container">
  <div class="main">
    <h1>
      This is the title
    </h1>
    <p>This is a paragraph paragraphparagraphpararrrrrgrapaaaaaaaaaah.</p>
  </div>

</div>
like image 137
Hiren Vaghasiya Avatar answered Sep 12 '26 21:09

Hiren Vaghasiya