Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS center display inline block?

Tags:

css

People also ask

How do you center with display inline block?

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.

How do I center an inline block image in CSS?

How to Center an Image Using Text Align: Center. An <img> element is an inline element (display value of inline-block ). It can be easily centered by adding the text-align: center; CSS property to the parent element that contains it.

How do I center an inline element in CSS?

To center an inline element like a link or a span or an img, all you need is text-align: center . For multiple inline elements, the process is similar. It's possible by using text-align: center .

How do I center an inline block in HTML?

Try using this: margin: 0 auto; Or text-align: center; on the parent <div> ...


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;
}

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;
}
<div class="parent">
  <a class="child" href="#0">Button</a>
</div>

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.


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%);
  }