Centering floating divs within another div

前端 未结 7 2118
自闭症患者
自闭症患者 2020-11-29 14:58

I\'ve searched other questions and, while this problem seems similar to a couple of others, nothing I\'ve seen so far seems to address the issue that I\'m having.

I

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-29 15:56

    In my case, I could not get the answer by @Sampson to work for me, at best I got a single column centered on the page. In the process however, I learned how the float actually works and created this solution. At it's core the fix is very simple but hard to find as evident by this thread which has had more than 146k views at the time of this post without mention.

    All that is needed is to total the amount of screen space width that the desired layout will occupy then make the parent the same width and apply margin:auto. That's it!

    The elements in the layout will dictate the width and height of the "outer" div. Take each "myFloat" or element's width or height + its borders + its margins and its paddings and add them all together. Then add the other elements together in the same fashion. This will give you the parent width. They can all be somewhat different sizes and you can do this with fewer or more elements.

    Ex.(each element has 2 sides so border, margin and padding get multiplied x2)

    So an element that has a width of 10px, border 2px, margin 6px, padding 3px would look like this: 10 + 4 + 12 + 6 = 32

    Then add all of your element's totaled widths together.

    Element 1 = 32
    Element 2 = 24
    Element 3 = 32
    Element 4 = 24
    

    In this example the width for the "outer" div would be 112.

    .outer {
      /* floats + margins + borders = 270 */
      max-width: 270px;
      margin: auto;
      height: 80px;
      border: 1px;
      border-style: solid;
    }
    
    .myFloat {
        /* 3 floats x 50px = 150px */
        width: 50px;
        /* 6 margins x 10px = 60 */
        margin: 10px;
        /* 6 borders x 10px = 60 */
        border: 10px solid #6B6B6B;
        float: left;
        text-align: center;
        height: 40px;
    }
    Float 1
    Float 2
    Float 3

提交回复
热议问题