Hallo zusammen!
Ich möchte per JavaScript herausfinden, welchen margin-left (-right) ein bestimmtes Element besitzt. Normalerweise ist das kein Problem:
window.getComputedStyle(element, false).marginLeft
Das klappt aber leider bei manchen Block-Elementen nicht, wenn diese "margin: auto" besitzen; dann liefert getComputedStyle nämlich 0.
Testcase:
<head>
<title>Test</title>
<style type="text/css">
p { background: yellow; margin: auto; width: 300px;}
</style>
</head>
<body>
<p id="p"></p>
<script type="text/javascript">
var p = document.getElementById('p');
p.appendChild(document.createTextNode(
'margin-left: '
+ window.getComputedStyle(p, false).marginLeft
));
</script>
</body>
Erst mal habe ich so meine Zweifel, ob das korrekt ist, denn:
http://www.w3.org/TR/CSS2/visudet.html#q6
If 'left' or 'right' are given as 'auto', their computed value is 0.
The following constraints must hold between the other properties:
'margin-left' + 'border-left-width' + 'padding-left' + 'width'
+ 'padding-right' + 'border-right-width' + 'margin-right' = width of containing block
[...]
If both 'margin-left' and 'margin-right' are 'auto', their computed values are equal.
Im Testcase sind die borders und paddings 0. Somit müsste 'margin-left' = 'margin-right' = (Breite von Body - width)/2 sein. Gerendert wird es ja richtig, aber getComputedStyle liefert 0. Bug im Firefox?
Da das nun mal nicht funktioniert, gibt es irgendeine andere Möglichkeit?
Vielen Dank schon mal!