CSS CSS Basics Getting Started with CSS Intro to CSS Review

2 Answers

Joel Bardsley
Joel Bardsley
31,199 Points

You have a few options. The easiest way is to set the parent element of the inline-block to text-align: center.

Otherwise there are two methods involving relative positioning:

.myButton {
  position: relative;
  left: 50%; /* the left edge of the button is now in the center of the parent element. Now we need to nudge the button back to the left by 50% of the button width to make it center aligned. */
  margin-left: -100px; /* If you've set a width for your button (in this case, 200px), enter 50% of its value here. Note that if you set margin-left: -50%, this will move the button -50% of the parent element, which will return it to the far left side. */
}

or

.myButton {
  position: relative;
  left: 50%;
  transform: translateX(-50%); /* this will calculate what 50% of the element width is and will move it across the X-axis. The negative value ensures it moves to the left. */
}

More information on CSS Transforms here

Matthew Francis
Matthew Francis
6,943 Points
.class{
position:relative/absolute;
left:50%; //Moves the element to the left by 50%
transform: translateX(-50%); //get half of the element's width and subtract that value with left's value
}