How to align 3 divs (left/center/right) inside another div?

前端 未结 18 2581
猫巷女王i
猫巷女王i 2020-11-21 20:48

I want to have 3 divs aligned inside a container div, something like this:

[[LEFT]       [CENTER]        [RIGHT]]

Container div is 100% wid

18条回答
  •  轮回少年
    2020-11-21 21:30

    I like my bars tight and dynamic. This is for CSS 3 & HTML 5

    1. First, setting the Width to 100px is limiting. Don't do it.

    2. Second, setting the container's width to 100% will work ok, until were talking about it being a header/footer bar for the whole app, like a navigation or credits/copyright bar. Use right: 0; instead for that scenario.

    3. You are using id's (hash #container, #left, etc) instead of classes (.container, .left, etc), which is fine, unless you want to repeat your style pattern elsewhere in your code. I'd consider using classes instead.

    4. For HTML, no need to swap order for: left, center, & right. display: inline-block; fixes this, returning your code to something cleaner and logically in order again.

    5. Lastly, you need to clear the floats all up so that it doesn't mess with future

      . You do this with the clear: both;

    To summarize:

    HTML:

    CSS:

    .container {right: 0; text-align: center;}
    
    .container .left, .container .center, .container .right { display: inline-block; }
    
    .container .left { float: left; }
    .container .center { margin: 0 auto; }
    .container .right { float: right; }
    .clear { clear: both; }
    

    Bonus point if using HAML and SASS ;)

    HAML:

    .container
      .left
      .center
      .right
      .clear
    

    SASS:

    .container {
      right: 0;
      text-align: center;
    
      .left, .center, .right { display: inline-block; }
    
      .left { float: left; }
      .center { margin: 0 auto; }
      .right { float: right; }
      .clear { clear: both; }
    }
    

提交回复
热议问题