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.
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.
Note: We can see that the “text-align : center” is not centering the block elements. They are only centering the non-block or inline-block elements. Center block elements using margin property: We need to specify the margin from left and right such that it looks centered.
CSS Layout - display: inline-block. ❮ Previous Next ❯. Compared to display: inline, the major difference is that display: inline-block allows to set a width and height on the element. Also, with display: inline-block, the top and bottom margins/paddings are respected, but with display: inline they are not.
CSS Layout - Horizontal & Vertical Align. ❮ Previous Next ❯. To horizontally center a block element (like <div>), use margin: auto; Setting the width of the element will prevent it from stretching out to the edges of its container.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With