4

I have a popup which is positioned in the center of the screen with: transform: translate(-50%, -50%); and position: absolute. Unfortunately for some reason my width is fixed and it is not dynamic ( based on the content ).

This is my jsfiddle: https://jsfiddle.net/qh13mnaf/1/

Why the width of the popup is not bigger?

Hristo Eftimov
  • 13,845
  • 13
  • 50
  • 77
  • 1
    Because your are giving `.tabs` and `.tabs-content` a fixed width. – NiZa Mar 04 '16 at 13:32
  • Even with only text without any html is not working so good. With `width` property it is ok. For example: [https://jsfiddle.net/qh13mnaf/2/](https://jsfiddle.net/qh13mnaf/2/) I understand that width is based on the device with, but on my tablet I have to much space between the end of the screen and the popup. How to make the popup's width to be the width of the longest element: for example the title – Hristo Eftimov Mar 04 '16 at 13:47
  • Are you able to add jQuery to your code? Although: You want the div to be horizontal and vertical aligned and although be exact as big as needed to display the content in it (not bigger)? – Marian Rick Mar 04 '16 at 14:02
  • You could try a flexbox solution? See [this SO question](http://stackoverflow.com/questions/19026884/flexbox-center-horizontally-and-vertically) – Yoeri Mar 04 '16 at 14:07

1 Answers1

8

Solution:

Set .popup-content { width: 100%; } and nest your content inside another div display: table; margin: 0 auto;

JSFIDDLE DEMO

Explanation:

Your centered div .popup-content has the attribute left: 50%, which means it will leave the left half of its parent blank. This means, that the div sets its own width to all of the width of its parent that is left, which although will be 50%.

For example if you set .popup-contents width to left: 30%, it will use 70% of its parents width.

Your second css attribute transform: translate(-50%, -50%); only does move the whole div, without changing (or influencing) its width.

CSS derivation:

I guess you want the div to be only as big as needed and centered both, horizontal and vertical. If thats right, heres a step by step solution:

As your css does a good job of centering it vertical, you can keep this, but simply set its width to 100%:

.popup-content {
  position: absolute;
  top: 50%;
  width: 100%;
  transform: translate(0%, -50%);
}

Next you can nest your content inside another div to center it horizontal using display: table;

.popup-center-horizontal {
  display: table;
  margin: 0 auto;
  background: red;
}

You can check a working demo right here JSFIDDLE DEMO.

If you do not want your div to reach the side, you can set a max-width to limit its size, for example:

.popup-center-horizontal {
   max-width: 90%;
}

Works on IE8+.

Marian Rick
  • 3,350
  • 4
  • 31
  • 67