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

前端 未结 18 2363
猫巷女王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:19

    Aligning Three Divs Horizontally Using Flexbox

    Here is a CSS3 method for aligning divs horizontally inside another div.

    #container {
      display: flex;                  /* establish flex container */
      flex-direction: row;            /* default value; can be omitted */
      flex-wrap: nowrap;              /* default value; can be omitted */
      justify-content: space-between; /* switched from default (flex-start, see below) */
      background-color: lightyellow;
    }
    #container > div {
      width: 100px;
      height: 100px;
      border: 2px dashed red;
    }

    jsFiddle

    The justify-content property takes five values:

    • flex-start (default)
    • flex-end
    • center
    • space-between
    • space-around

    In all cases, the three divs are on the same line. For a description of each value see: https://stackoverflow.com/a/33856609/3597276


    Benefits of flexbox:

    1. minimal code; very efficient
    2. centering, both vertically and horizontally, is simple and easy
    3. equal height columns are simple and easy
    4. multiple options for aligning flex elements
    5. it's responsive
    6. unlike floats and tables, which offer limited layout capacity because they were never intended for building layouts, flexbox is a modern (CSS3) technique with a broad range of options.

    To learn more about flexbox visit:

    • Methods for Aligning Flex Items
    • Using CSS flexible boxes ~ MDN
    • A Complete Guide to Flexbox ~ CSS-Tricks
    • What the Flexbox?! ~ YouTube video tutorial

    Browser support: Flexbox is supported by all major browsers, except IE < 10. Some recent browser versions, such as Safari 8 and IE10, require vendor prefixes. For a quick way to add prefixes use Autoprefixer. More details in this answer.

提交回复
热议问题