CSS center display inline block?

后端 未结 9 1693
误落风尘
误落风尘 2020-11-22 08:25

I have a working code here: http://jsfiddle.net/WVm5d/ (you might need to make the result window bigger to see the align center effect)

Question

相关标签:
9条回答
  • 2020-11-22 09:03

    The accepted solution wouldn't work for me as I need a child element with display: inline-block to be both horizontally and vertically centered within a 100% width parent.

    I used Flexbox's justify-content and align-items properties, which respectively allow you to center elements horizontally and vertically. By setting both to center on the parent, the child element (or even multiple elements!) will be perfectly in the middle.

    This solution does not require fixed width, which would have been unsuitable for me as my button's text will change.

    Here is a CodePen demo and a snippet of the relevant code below:

    .parent {
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    .child {
      display: inline-block;
    }
    <div class="parent">
      <a class="child" href="#0">Button</a>
    </div>

    0 讨论(0)
  • 2020-11-22 09:08

    If you have a <div> with text-align:center;, then any text inside it will be centered with respect to the width of that container element. inline-block elements are treated as text for this purpose, so they will also be centered.

    0 讨论(0)
  • 2020-11-22 09:12

    Just use:

    line-height:50px

    Replace "50px" with the same height as your div.

    0 讨论(0)
  • 2020-11-22 09:13

    Great article i found what worked best for me was to add a % to the size

    .wrap {
    margin-top:5%;
    margin-bottom:5%;
    height:100%;
    display:block;}
    
    0 讨论(0)
  • 2020-11-22 09:14

    Try this. I added text-align: center to body and display:inline-block to wrap, and then removed your display: table

    body {
        background: #bbb;
        text-align: center;
    }
    
    .wrap {
        background: #aaa;
        margin: 0 auto;
        display: inline-block;
        overflow: hidden;
    }
    
    0 讨论(0)
  • 2020-11-22 09:15

    You can also do this with positioning, set parent div to relative and child div to absolute.

    .wrapper {
          position: relative;
      }
    .childDiv {
          position: absolute;
          left: 50%;
          transform: translateX(-50%);
      }
    
    0 讨论(0)
提交回复
热议问题