Alexander Rodin
Alexander Rodin

Reputation: 81

Center absolute block with transform: translate(-50%, -50%) way issue

Here is my example:

body {
  padding: 50px;
}

div {
  width: 240px;
  height: 150px;
  border: 1px solid #ccc;
  position: relative;
}

a {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <div>
    <a href="">Lorem ipsum dolor sit.</a>
  </div>
</body>
</html>

I would like to center my absolute positioned text in block using left: 50%; top: 50%; transform: translate(-50%, -50%);, but my text have line break. Obviously, my block has enough space to place in one line the text. I'm not sure, but may be there is a way to solve this problem?

Upvotes: 1

Views: 2890

Answers (3)

Johannes
Johannes

Reputation: 67778

The left: 50% causes the a element to have only 50% width, i.e. 50% of the parent element, since it starts in the middle and extends to the right border. So its contents wrap in your case, since they won't fit into 50% width.

I would suggest an alternative solution where flexbox does the centering (actually results in less CSS):

body {
  padding: 50px;
}

div {
  width: 240px;
  height: 150px;
  border: 1px solid #ccc;
  display: flex;
  justify-content: center;
  align-items: center;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <div>
    <a href="">Lorem ipsum dolor sit.</a>
  </div>
</body>

</html>

Upvotes: 1

tobiv
tobiv

Reputation: 842

You can use CSS flexbox module for that. All you need is to set the containing element to display: flex and use align-items and justify-content properties to set the alignment of the content. The a element in this case doesn't need any special styling. Here's a nice flexbox guide.

body {
  padding: 50px;
}

div {
  display: flex;
  align-items: center;
  justify-content: center;

  width: 240px;
  height: 150px;
  padding: 1em;
  border: 1px solid #ccc;
  position: relative;
}
<body>
  <div>
    <a href="#">The content is centered in the flex box no matter how many lines of text you have.</a>
  </div>
</body>

Upvotes: 0

curveball
curveball

Reputation: 4505

Try to add

a { white-space: nowrap; }

It should keep it as 1 line.

Also you could get rid of all this positioning: just a {line-height: 150px;} and add text-align: center; to div:

body {
  padding: 50px;
}

div {
  width: 240px;
  height: 150px;
  border: 1px solid #ccc;
  text-align: center;
}

a {
  line-height: 150px;
}
  <div>
    <a href="">Lorem ipsum dolor sit.</a>
  </div>

Upvotes: 2

Related Questions