Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How to horizontally center an element in HTML CSSLanguage ?

How can I horizontally center a <div> within another <div> using CSS?

<div id="outer">
<div id="inner">Foo foo</div>
</div>
by

2 Answers

Bharatgxwzm
In the event that you would prefer not to set a fixed width on the inward div you could accomplish something like this:
#outer {
width: 100%;
text-align: center;
}

#inner {
display: inline-block;
}

<div id="outer">  
<div id="inner">Foo foo</div>
</div>

That makes the internal div into an inline component that can be focused with text-align.
Shahlar1vxp
In order to horizontally centre an element, you first need to ensure that the parent element is positioned as relative, fixed, sticky or absolute. The code is as follows-
.centered {
position: absolute;
left: 50%;
margin-left: -100px;
}

In this case, the width of your element or div is 200 pixels.
In case you do not know the width of your element or div, then you can use the following code instead of a negative margin-
transform: translateX (-50%);
And by using CSS calc() property, it gets even simpler:
.centered {
width: 200px;
position: absolute;
left: calc (50% - 100px);
}

Login / Signup to Answer the Question.