JS style.marginLeft& marginRight ='auto'无效

时间:2016-06-09 14:53:57

标签: javascript html css

使用Yahoo Weather API。

当尝试通过JS设置样式边距时,没有任何反应。

这是我的剧本:

<script>
var cBackFunction = function (data) {
    console.log(data);

    var location = data.query.results.channel.location;
    var condition = data.query.results.channel.item.condition;
    var wind = data.query.results.channel.wind;
    var units = data.query.results.channel.units;
    var link = data.query.results.channel.link;
    var lastUpdated = data.query.results.channel.lastBuildDate;
    var conditionCode = condition.code;
    var conditionText = condition.text;

    var img = document.createElement("IMG");
    img.src = "https://s.yimg.com/zz/combo?a/i/us/we/52/" + conditionCode + ".gif";
    img.style.marginLeft = "140px";

    document.getElementById('Weather-Description2').appendChild(img);

    document.getElementById('Weather-Location2').innerHTML = location.city;
    document.getElementById('Weather-Region2').innerHTML = location.region;
    document.getElementById('Weather-Temp2').innerHTML = condition.temp;
    document.getElementById('Weather-Unit2').innerHTML = units.temperature;
    document.getElementById('Weather-WindSpeed2').innerHTML = wind.speed;
    document.getElementById('Weather-Link2').href = link;
    document.getElementById('lastUpdate2').innerHTML = lastUpdated;
    document.getElementById('Weather-text2').innerHTML = "["+conditionText+"]";
    document.getElementById('Weather-text2').style.marginLeft = 'auto';     //not working
    document.getElementById('Weather-text2').style.marginRight = 'auto';     // not working
}

HTML:

<strong id="Weather-text2"></strong>

如果我将auto更改为特定像素,例如“100px”那么它可以正常工作..可以在JS中使用auto作为边距吗? automarginLeftmarginRight的原因是自动居中元素。如果是这样,我该如何正确实现?

1 个答案:

答案 0 :(得分:3)

默认情况下,<strong>元素为display: inline

自动边距中心元素为display: block(虽然您将width: auto作为默认值,但除非您缩小宽度,否则这将没有实际效果。)

在最近的块祖先元素上设置text-align: center以使文本居中。