CSS paragraph layout with a border, and ::before element that needs its own border

172 views Asked by At

I've got some text that needs the following:

  • border around the text
  • a ::before element that has its own border and background color

Basically, I want it to look like this:

enter image description here

So far, I've got this:

enter image description here

My CSS:

 .caution {
    border: 0.5pt solid black;
    padding-left: 3pt; 
    padding-right: 3pt;
   display: table;
}

.caution::before {
    display: table-cell;
    border: 0.5pt solid black;
    background-color: #deddde;
    text-align: center;
    content: "caution";
}

My html:

<p class="caution">Caution text</p>

The result is that the ::before box is nested inside the .caution box, instead of overlapping. The gaps on the left and right are caused by the padding-left and padding-right statements.

I've also tried this without the display:table, that didn't help. I need the padding-left and padding-right to apply to the text (to ensure the text doesn't come right up to the border), but not to the ::before element. There's no selector that allows me to apply properties to 'all of .caution except the ::before element'.

How can I get the borders to behave the way I want them to?

3

There are 3 answers

1
Labu On BEST ANSWER

You can try this - it's not perfect, but it's a start :)

.caution {
  border: 0.5pt solid black;
  display: inline-block;
  max-width: 200px;
  padding: 10px;
}

.caution::before {
  display: block;
  border-bottom: 0.5pt solid black;
  margin: -10px;
  margin-bottom: 10px;
  background-color: #deddde;
  text-align: center;
  content: "Caution";
}

It will render the following:

enter image description here

1
Yogendra Chauhan On

Here is the working example:

.caution {
    position: relative;
    border: 1px solid #000000;
    height: 200px;
    width: 300px;
    padding-left: 5px;
    padding-right: 5px;
    padding-top: 30px;
}

.caution::before {
    position: absolute;
    background-color: #deddde;
    text-align: center;
    content: "caution";
    text-transform: capitalize;
    display: block;
    width: 100%;
    border-bottom: 1px solid #000000;
    top: 0;
    left: 0;
    line-height: 25px;
}
<div class="caution">Caution text</div>

0
Tony Graham On

Setting only border-bottom (as in answer by Yogendra Chauhan, though I only noticed that afterwards) can help:

.caution {
    border: 0.5pt solid black;
    padding-left: 3pt; 
    padding-right: 3pt;
    display: block;
}

.caution::before {
    border-bottom: 0.5pt solid black;
    background-color: #deddde;
    text-align: center;
    content: "caution";
    display: block;
    margin: 0 -3pt;
}

However, you might see a small white line at the ends of the bottom border when you zoom to 6,400% in your PDF viewer.