Text is breaking using absolute positioning

巧了我就是萌 提交于 2019-12-04 03:02:34

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)

Here, I have made a few minor CSS changes for you.

/* Cosmetics */
* { box-sizing: border-box; }
body { margin: 50px; }
p { margin: 0; }


/* True Code */
.content {
  border: 3px double black;
  padding-top: 30px;
  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;
  white-space: nowrap;
  margin-top: 0px;
}

your code was correct but the left attribute spoiled your output. as your .content div was set to relative, the .title will remain inside it. So you just need to change the position your .title using transform: translate(); code. And voila you got your desired output.

You might notice i have given padding-top to the .content just to place the heading in a proper place.

the changed code is as follows :

/* Cosmetics */
* { box-sizing: border-box; }
body { margin: 50px; }
p { margin: 0; }


/* True Code */
.content {
  border: 3px double black;
  padding-top:10px;
  position: relative;
  width: 350px;
}

.content p { margin: 20px; }

.title {
  background: black;
  border-radius: 5px;
  color: white;
  padding: 10px;
  position: absolute;
  transform: translate(22%,-110%);
}

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!