Aligning inline-block center

35,244

Like this? http://jsfiddle.net/bcL023ko/3/ Remove the float:left left and add margin: 0 auto to center the element. Or is it something else that your are looking for?

Share:
35,244
Andrew
Author by

Andrew

Updated on October 31, 2020

Comments

  • Andrew
    Andrew over 3 years

    What would be the easiest way to center align an inline-block element?

    Ideally, I don't want to set a width to the elements. This way depending on the text inputted within the elements, the inline-block element will expand to the new width without having to change the width within the CSS. The inline-block elements should be centered on top of one another (not side by side), as well as the text within the element.

    See code below or see on jsFiddle.

    The current HTML:

    <div>
      <h2>Hello, John Doe.</h2>
      <h2>Welcome and have a wonderful day.</h2>
    </div>
    

    The current SCSS:

    @import url(http://fonts.googleapis.com/css?family=Open+Sans:400,300,600);  
    
    body {
        margin: 0 auto;
        background: rgba(51,51,51,1);
        font-family: 'Open Sans', sans-serif;
    }
    
    div {
        width: 100%;
        height: auto;
        margin: 15% 0;
        text-align: center;
        h2 {
            margin: 0 auto;
            padding: 10px;
            text-align: center;
            float: left;
            clear: left;
            display: inline-block;
            &:first-child {
                color: black;
                background: rgba(255,255,255,1);
            }
            &:last-child {
                color: white;
                background: rgba(117,80,161,1);
            }
        }
    }
    

    Adding a br between the two elements and taking out the float: left/clear: left may be the easiest way; however, I was curious if there was another way going about this.