Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: How to position a div in the center with dynamic width

Tags:

html

css

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?

like image 540
Hristo Eftimov Avatar asked Mar 13 '23 01:03

Hristo Eftimov


1 Answers

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+.

like image 58
Marian Rick Avatar answered May 01 '23 22:05

Marian Rick