user4493177
user4493177

Reputation: 790

Centered fixed div with width fit to content

I am trying to have a fixed div (position: fixed) in the center of the page. So far that works with this css:

#msg{
  border: 1px solid black;
  position: fixed;
  z-index: 9999;
  background-color: white;
  bottom: 0px;
  top: 0px;
  left: 0px;
  right: 0px;
  margin: auto;
  width: 100px;
  height: 100px;
  padding: 5px;
}
<div id="msg"> Hello </div>

The only thing that is not working, is trying to get the size of the div (width, if possible also height) to automatically match the size of the content in it.

So basically a normal div like this, but then fixed and centered:

#msg2{
  border: 1px solid;
  display: inline-block;
}
<div id="msg2"> hello </div>

I am looking for a non-javascrpit solution

Upvotes: 2

Views: 2427

Answers (2)

John Slegers
John Slegers

Reputation: 47081

For a very robust way to center your #msg, consider the following technique.


You just need two containers!

1. The outer container :

  • should have display: table;

2. The inner container :

  • should have display: table-cell;
  • should have vertical-align: middle;
  • should have text-align: center;

3. The #msg box itself :

  • should have display: inline-block;
  • should have eg. text-align: left; or text-align: right; if you don't want your text-alignment centered.

You can add any content you want to the content box without caring about its width or height!

Demo :

body {
    margin : 0;
}

#outer-container {
    position : fixed;
    display: table;
    width: 100%;
    height: 100%;
    background: #ccc;
}

#inner-container {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}

#msg {
    text-align: left;
    display: inline-block;
    background: #fff;
    padding : 20px;
    border : 1px solid #000;
}
<div id="outer-container">
   <div id="inner-container">
     <div id="msg">
        Hello
     </div>
   </div>
</div>

See also this Fiddle!

Upvotes: 0

Marcos P&#233;rez Gude
Marcos P&#233;rez Gude

Reputation: 22158

You can use translate to perfect center without pre-knowing the width and/or height of the box.

The solution is to put 50% from top and left and then translate to the opposite -50% (X and Y axis):

#msg2{
  border: 1px solid;
  display: inline-block;
  position: fixed;
  top:50%;
  left:50%;
  -webkit-transform: translate(-50%, -50%); /* iOS needed */
  transform: translate(-50%, -50%);
}
<div id="msg2"> hello </div>

Upvotes: 4

Related Questions