2014-05-16 5 views
0

모든 하위 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> 

답변

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합니다.

하지만 float로 멋지고 빡빡합니다. 왼쪽은 Screenshot입니다.

여분의 공간에 대한 자세한 내용은 here을 참조하십시오.

+0

작동합니다! 왜 지구상에서 그게 효과가 있니?! –

+0

위의 링크를 통해 내 대답을 편집했습니다. – Sammy

+1

고맙습니다. –

관련 문제