Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Text is breaking using absolute positioning

Tags:

html

css

absolute

I have a small challenge that I haven't found any solution on Stack Overflow.

That's what I got:

wrong

And that's how I'd like it:

correct

To produce this title effect I'm using absolute position. I don't even know the width and the height from my title. So, big text breaks when using this solution.

My HTML:

<div class="content">
  <h1 class="title">February 2015</h1>
  <p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo. Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>
</div>

My CSS:

.content {
  border: 3px double black;
  padding-top: 60px;
  position: relative;
  width: 350px;
}

.content p { margin: 20px; }

.title {
  background: black;
  border-radius: 5px;
  color: white;
  left: 50%;
  padding: 10px;
  position: absolute;
  text-align: center;
  transform: translate(-50%, -50%);
  top: 0;
}

See an example on Codepen to make life easier: http://codepen.io/caio/pen/ZYoyPb

like image 874
Caio Tarifa Avatar asked Feb 23 '15 18:02

Caio Tarifa


People also ask

What is absolute positioning used for?

This is a very powerful type of positioning that allows you to literally place any page element exactly where you want it. You use the positioning attributes top , left , bottom , and right to set the location.

Why is position Absolute taking space?

position: absolute means they don't occupy space in the flow. However, you don't have to animate using margin, you can use float to let the elements take up whatever space, and make each of the elements position:relative .


2 Answers

There is another solution:

.title {
    width: max-content;
}

It is widely supported (92.25% as of 17.07.2019) https://caniuse.com/#feat=intrinsic-width

For details read this answer.

like image 84
Ed Kolosovsky Avatar answered Oct 01 '22 01:10

Ed Kolosovsky


The easiest solution would be to add white-space: nowrap. In doing so, the h1 text will not break to a new line. (updated example)

.title {
  white-space: nowrap;
  background: black;
  border-radius: 5px;
  color: white;
  left: 50%;
  padding: 10px;
  position: absolute;
  text-align: center;
  transform: translate(-50%, -50%);
  top: 0;
}

In addition, you could also add text-overflow: ellipsis/overflow: hidden/width: 100% so that the text forms ellipsis and never breaks to a new line. (example here)

like image 31
Josh Crozier Avatar answered Oct 01 '22 01:10

Josh Crozier