Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a border in css that doesn't change size?

Tags:

html

css

So I have this code:

<h1 id="result" style="color:black; font-family: Bradley Hand; font-size:50px; position:absolute; top:17%; left:60%">
    text
</h1>

How can I make a border that if I put a longer text in, my border will keep its position and change its size, to make my text still in the border? Thanks!

like image 895
Steven Tran Avatar asked Dec 17 '25 13:12

Steven Tran


1 Answers

Just adding border: 1px solid black (for example) to what you have works perfectly fine. The h1 element will grow and shrink to fit it's content and the border will do so as well:

const result = document.getElementById('result');
const sentence = "HELLO! IT LOOKS LIKE THIS IS WORKING FINE...";

let index = 0;

setInterval(() => {
  index = (index % sentence.length) + 1;

  result.innerHTML = sentence.slice(0, index);
}, 250);
#result {
  position:absolute;
  top: 10%;
  left: 10%;
  padding: 0 .5rem;
  font-family: Sans-Serif;
  font-size: 2rem;
  line-height: 3rem;
  color: black;
  border: 3px solid black;
  border-radius: 3px;
  min-height: 3rem;
}
<h1 id="result"></h1>

Anyway, I suspect you may be referring to the border changing your element's dimension:

#bar1 {
  width: 50%;
  height: 1rem;
  background: red;
  margin: .25rem;
}

#bar2 {
  width: 50%;
  height: 1rem;
  background: cyan;
  margin: .25rem;
  border: 3px solid black;
}
<div id="bar1"></div>
<div id="bar2"></div>

That's because by default, your element's width and height are actually a sum of the specified width and height properties, plus padding plus border, as you can see from the example above.

If that's the case, you have two options to keep the dimensions just as specified with width and height:

  • Using box-sizing: border-box. That will make padding and border included in the element's total width and height.

  • Using box-shadow instead of border. You can use the inset property to draw the shadow to the inside of the element instead of to the outside.

#bar1 {
  width: 50%;
  height: 1rem;
  background: red;
  margin: .25rem;
}

#bar2 {
  width: 50%;
  height: 1rem;
  background: cyan;
  margin: .25rem;
  border: 3px solid black;
  box-sizing: border-box;
}

#bar3 {
  width: 50%;
  height: 1rem;
  background: yellow;
  margin: .25rem;
  box-shadow: inset 0 0 0 3px black;
}

#bar4 {
  width: 50%;
  height: 1rem;
  background: lime;
  margin: .25rem;
  box-shadow: 0 0 0 3px black;
}
<div id="bar1"></div>
<div id="bar2"></div>
<div id="bar3"></div>
<div id="bar4"></div>

Note the 4th bar, the one with the outer box-shadow looks bigger, but if you inspect it, its dimensions are exactly the same as those in the other 3 bars.

like image 114
Danziger Avatar answered Dec 19 '25 05:12

Danziger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!