Warm tip: This article is reproduced from stackoverflow.com, please click
css styled-components

Is there an way to make text stick to div "border"?

发布于 2020-03-27 10:15:22

I've been trying to find a way to have a similar effect to the common "stick to the top of a container" but instead of the top, i'm trying to make it stick to the border of a container always in the same place, but i keep getting the text to just keeps moving around when the resolution changes: In Higher resolutions it stays in the right place, but when the resolution diminishes or get way to high, the text starts dancing around the container.
To clarify, i'm using styled-components for the container and inline-css for the text, i've already tried "responsive" css using screen.size to change the marginTop when the screen size changes, but it didn't seem effective or browser-friendly at all and was also really confusing to read, so i hope there's a better way to do this, i'm sorry if this question seems way to stupid and/or was already answered, i've search a lot about it but didn't find anything that fitted the context and worked.

.fieldset{
  width: 97%;
  margin: auto;
  background: #00000000;
  padding: 1%;
  border-radius: 5px;
  border: 3px solid gray;
  min-height: 50px;
}

.title{
  margin-top: -1rem;
  font-family: "Helvetica";
  color: "grey";
  background: "white";
  width: 10em;
}
<div class="fieldset">
<h3 class="title">
        Title
      </h3>
      <p>a</p>
</div>
Questioner
Matheus Castro
Viewed
114
Dawid Schmidt 2019-12-10 18:33

Your padding is changing so you cant control it. If you really want to have dynamic padding you have to set set them same value like 1vw, and them calc position of .title like calc(-12px - 1vw);

.fieldset{
  width: 97%;
  margin: auto;
  background: #00000000;
  padding: 1vw;
  border-radius: 5px;
  border: 3px solid gray;
  min-height: 50px;
}

.title {
    margin: 0;
    position: relative;
    top: calc(-12px - 1vw);
    font-family: "Helvetica";
    width: 10em;
}
<div class="fieldset">
<h3 class="title">
        Title
      </h3>
      <p>a</p>
</div>