Div Container horizontal und vertikal zentrieren

Div Container lassen sich mit absoluter Positionierung und Minusabständen zentrieren (siehe [post id=3140][/post]). Meine neue Lieblingsmethode, um einen Div Container mittig zu platzieren, ist aber Folgende:

<!DOCTYPE html>
<html>
  <head>
    <title></title>
    <meta charset="UTF-8">
    <style>
      #wrapper {
        width: 400px;
        height: 400px;
 
        position: relative;
        display: table-cell;
        vertical-align: middle;
        text-align: center;
 
        background-color: black;
      }
 
      #center {
        width: 200px;
        height: 200px;
 
        position: relative;
        display: inline-block;  
 
        background-color: yellow;
      }
    </style>
  </head>
  <body>
    <div id="wrapper">
      <div id="center"></div>
    </div>
  </body>
</html>

Bild in einem SVG-Element zentrieren

Man kann ein Bild in einem SVG-Element wie folgt zentrieren:

<svg id="box" width="200" height="200">
<image 
  width="114" 
  height="158" 
  xlink:href="images/card.png"
 
  x="50%" 
  y="50%" 
  transform="translate(-57, -79)"
  >
</image>
</svg>

In Worten:

  1. Obere linke Ecke des Bildes in der Mitte der Fläche ansetzen (x="50%", y="50%")
  2. Bild um die Hälfte der Bildgröße nach links verschieben (-57)
  3. Bild um die Hälfte der Bildhöhe nach oben verschieben (-79

Div Element horizontal und vertikal zentrieren

Ein Code sagt mehr als tausend Worte:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Centering a Div horizontally and vertically</title>
    <style type="text/css">
      html
      {
        background-color: black;
      }
 
      body
      {
        width: 100%;
        height: 100%;
        position: static; /* don't make it relative! */
      }
 
      #centered
      {
        position: absolute;
        height: 396px;
        width: 400px;
        margin: -198px 0px 0px -200px; /* 50% height, 0px, 0px, 50% width */
        top: 50%;
        left: 50%;
        background-color: violet;
        border: 1px solid white;
      }
    </style>
  </head>
  <body>  
    <div id="centered"></div>
  </body>
</html>

DIV im IE zentrieren

Falls der Internet Explorer die Angabe margin: auto; zum Zentrieren von DIV-Containern nicht befolgt, dann hilft dieser Trick:

#container
{
	position: relative;
	width: 600px;
	left: 50%;
	margin-left: -300px;
}

Mit left: 50%; wird der Container um 50% des Anzeigebereichs nach rechts verschoben. Das ist etwas zu viel, deshalb muss man die halbe Breite bei margin-left angeben, um die Verschiebung auszugleichen und das DIV mittig zu positionieren.