简体   繁体   English

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

[英]How to set parent width around dynamic elements

I'm trying to set the width of a parent div so that all of its child divs display on one line (horizontally). 我正在尝试设置父div的宽度,以使其所有子div都显示在一行上(水平)。 I'm looping through the children and using jQuery's outerWidth(true) function to find the total necessary width. 我正在遍历子级,并使用jQuery的outerWidth(true)函数来查找总必要宽度。 But although the calculation seems to be correct to me, the inner elements break onto two lines. 但是,尽管计算对我来说似乎是正确的,但内部元素分为两行。 I'm testing in Chrome, FF and Safari, and IE9. 我正在Chrome,FF和Safari以及IE9中进行测试。 What am I missing? 我想念什么?

<!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>

instead of inline-block, use float:left; 代替inline-block,使用float:left;

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

jsfiddle jsfiddle

With inline-block you have this extra white space: Screenshot . 使用inline-block,您将拥有以下额外的空白: 屏幕截图

But nice and tight with float: left Screenshot . 但是与float紧密配合:left 屏幕截图

You can read more about that extra space here . 您可以在此处阅读有关该额外空间的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM