Home > Mobile >  Centering Badge Along Top Edge Of Card Component
Centering Badge Along Top Edge Of Card Component

Time:05-26

I have a card component (the larger rectangle) and am hoping to have a badge (the smaller rectangle) positioned as seen in the image

Any thoughts on best approach?

enter image description here

(Have been attempting to leverage absolute positioning but having trouble coming up with a way to get it centered)

CodePudding user response:

If I understood you correctly, then to center absolutely placed elements, use the combination left: 50%; and transform: translateX(-50%);. Example below:

.container {
  height: 500px;
  width: 300px;
  border: 2px solid black;
  border-radius: 15px;
  position: relative;
  margin-top: 60px; /* just for a better look at the example */
}

.top-badge {
  position: absolute;
  top: -20px;
  left: 50%;
  transform: translateX(-50%);
  border: 3px solid black;
  background: whitesmoke;
  width: 100px;
  height: 50px;
}
<div >
  <div >

  </div>
</div>

CodePudding user response:

You can make use of fieldset and legend which will do that by default. You just have to center the legend by using margin: 0 auto:

legend {
  margin: 0 auto;
}


/* for visualization only */
fieldset {
  height: 60vh;
  width: 50vw;
  margin-top: 20vh;
}

legend {
  display: block;
  width: 20vw;
  height: 10vh;
  background-color: white;
}

fieldset, legend {
  border-radius: 10px;
  border: 2px solid black;
}
<fieldset>
  <legend></legend>
</fieldset>

Alterntivly you can also use position: relative position: absolute:

.title {
  position: absolute;
  top: 0;
  left: 50%;
  transform: translate(-50%, -50%);
}

which will center it perfectly vertically 50% of the titles height and horizontally in the exact center:

.box {
  position: relative;
}

.title {
  position: absolute;
  top: 0;
  left: 50%;
  transform: translate(-50%, -50%);
}


/* for visualization only */
.box {
  height: 60vh;
  width: 50vw;
  margin-top: 20vh;
}

.title {
  width: 20vw;
  height: 10vh;
  background-color: white;
}

div {
  border-radius: 10px;
  border: 2px solid black;
}
<div >
  <div ></div>
</div>

  • Related