如何在动态元素周围设置父宽度

时间:2014-05-16 18:29:58

标签: jquery html css

我正在尝试设置父div的宽度,以便所有子div显示在一行(水平)上。我循环遍历孩子并使用jQuery的outerWidth(true)函数来查找所需的总宽度。但是虽然计算对我来说似乎是正确的,但内部元素分为两行。我正在使用Chrome,FF和Safari以及IE9进行测试。我错过了什么?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>test</title>
    <style>
        #outer{
            width: 100px;
            height: 200px;
            padding: 0px;
        }
        .inner{
            display: inline-block;
            width: 20px;
            height: 20px;
            margin-right: 5px;
            margin-bottom: 5px;
            background-color: yellow;
        }
    </style>
</head>
<body>
    <div id="outer">
        <div class="inner">0</div>
        <div class="inner">1</div>
        <div class="inner">2</div>
        <div class="inner">3</div>
        <div class="inner">4</div>
        <div class="inner">5</div>
        <div class="inner">6</div>
        <div class="inner">7</div>
        <div class="inner">8</div>
        <div class="inner">9</div>
    </div>

    <script src="../js/jquery.1.11.0.js"></script>
    <script>
    $(document).ready(function() {
        var itemsWidthWithMargin = 0;
        $(".inner").each(function() {
            itemsWidthWithMargin += $(this).outerWidth(true);
        });
        $("#outer").width(itemsWidthWithMargin);
        alert(itemsWidthWithMargin);
    });
    </script>
</body>
</html>

1 个答案:

答案 0 :(得分:3)

而不是内联块,请使用float:left;

.inner{
            float:left;
            width: 20px;
            height: 20px;
            margin-right: 5px;
            margin-bottom: 5px;
            box-sizing:border-box;
            background-color: yellow;
        }

jsfiddle

使用内联块,您可以获得额外的空格:Screenshot

但浮动很好,很紧:左Screenshot

您可以阅读有关额外空间here的更多信息。