Reputation: 85
In the following code, I am struggling to align the li HELLO exactly in the center of the ul But it's getting shifted to the left side. Here, I am not looking for a solution (as I am trying to practice and understand the functionality through this code). But I am most importantly looking for a reason and explanation as to why is this happening.
Even though I have set the left/right margin of the li to auto. Then why is it not coming in the center of the ul ? For visual aid, I have created border for li so that you can easily spot it's exact position. I know that by decreasing/altering the width of the ul , this problem can be corrected. But is there no other way so that the text is aligned in the center automatically (without manually adjusting width,padding etc)? Also if I increase the length of the text or change its font size I want the text to be aligned in the center.
html body {
height: 100%;
width: 200px;
}
ul {
background-color: rgba(0,0,0,1);
height: 100px;
width: 150px;
}
li {
color: rgba(255,255,255,1);
margin-right: auto;
margin-left: auto;
list-style-type: none;
width: 50px;
text-align: center;
border: thin solid rgba(255,255,255,1);
float: left;
}
<ul>
<li>Hello</li>
</ul>
Upvotes: 2
Views: 7347
Reputation: 51
I'm seeing two issues here:
By default ul
elements render with padding to the left. This is what's given you that spacing and perhaps creating confusion around that element being pushed right.
Additionally, you're adding the float
property to your <li>
element. Remove that and you should see your <li>
centered.
ul {
padding: 0;
background-color: rgba(0,0,0,1);
height: 100px;
width: 150px;
}
li {
color: rgba(255,255,255,1);
margin-right: auto;
margin-left: auto;
list-style-type: none;
width: 50px;
text-align: center;
border: thin solid rgba(255,255,255,1);
}
Upvotes: 0
Reputation: 10786
It is slightly to the right because the ul
has a padding-left
by default; setting padding-left: 0;
to the ul
will make it go completely left. Then the li
isn't centered because you're floating it to the left with float: left;
this will make it ignore the margin: auto;
you have set. If you remove the float
the li
will be at the center.
I guess you used the float
because there will be more li's
in the list and you want them all on one line and centered in the ul
. In these cases what I usually do is:
ul {
text-align: center;
}
li {
display: inline-block;
}
EXAMPLE:
ul {
margin: 0;
padding: 0;
text-align: center;
}
li {
display: inline-block;
margin: 0 10px;
border: 1px solid black;
padding: 5px;
}
<ul>
<li>Example1</li>
<li>Example2</li>
<li>Example3</li>
</ul>
Upvotes: 3