0

enter image description here

This is what I am trying to achieve. I tried using absolute position and it seemed to work on one screen size but doesn't work for others.

.countdown {
  width: 200px;
  background: #b02d1b;
  margin: 0;
  border-radius: 5px;
  color: #fff;
  text-align: center;
  padding: 5px;
  position: absolute;
  z-index: 1;
}

.countdown-bg {
  width: 100%;
  border-top: solid 1px #ccc;
  position: absolute;
  margin: 12px;
}
<div class="countdown"> Final Hours </div>
<div class="countdown-bg"></div>
showdev
  • 28,454
  • 37
  • 55
  • 73
Suraj
  • 59
  • 1
  • 6

2 Answers2

2

I think I have a solution for your question:

.divOuter {
  background-color: #cccccc;
  width: 100%;
  height: 2px;
  position: absolute;
}

.divInner {
  background-color: #cc0000;
  width: 130px;
  height: 20px;
  position: relative;
  top: -12px;
  margin: 0 auto;
  color: #ffffff;
  text-align: center;
  font-family: Verdana;
  font-size: 0.8em;
  font-weight: bold;
  border-radius: 10px;
  border: 4px solid #ffffff;
}
<div class="divOuter">
  <div class="divInner">FINAL HOURS!</div>
</div>

Brief explanation:

We have two divs, the second one in the html is on top of the first one. This placement in CSS is called a float.

When we need this effect we use the "position" property of the CSS with values like Absotule and Relative.

In this case, the first Div makes the thin line and the second Div makes the red rectangle.

The "top", "left", "right" and "button" property of the css causes to align the second Div relative to the first. And the property "margin: auto" causes the internal div to be aligned to the center of the external div.

I hope I've helped!

Denis Jr
  • 346
  • 2
  • 11
2

Without flexbox

Wrapp one div inside another div. Make the outer div position: relative and the inner div position: absolute. Center the inner div with left and transform

.countdown {
  position: relative;
  border-top: solid 1px #ccc;
  margin: 15px 0;
}

.countdown>.content {
  width: 200px;
  text-align: center;
  background: #b02d1b;
  border-radius: 5px;
  color: #fff;
  padding: 5px;
  position: absolute;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 1;
  text-transform: uppercase;
}
<div class="countdown">
  <div class="content">Final Hours!</div>
</div>

With flexbox

The advantage of using flexbox is that you don't have to set positions and that you can center with justify-content.

.countdown {
  border-top: solid 1px #ccc;
  margin: 15px 0;
  display: flex;
  justify-content: center;
}

.countdown>.content {
  width: 200px;
  text-align: center;
  background: #b02d1b;
  border-radius: 5px;
  color: #fff;
  padding: 5px;
  transform: translateY(-50%);
  z-index: 1;
  text-transform: uppercase;
}
<div class="countdown">
  <div class="content">Final Hours!</div>
</div>
Community
  • 1
  • 1