How To Text Align Left And Center In Screen

时间:2015-09-14 15:20:35

标签: html css

I'm missing something simple. I have an ul with 3 li in it, and as of right now, it's resting against the left side of it's container. I want the lis to maintain their text-align: left look, but I want them to be centered horizontally in the div.

Note: I would like to veer away from tables And I would like to avoid widths that need to be adjusted at various screen sizes

HTML:

<div>
    <ul>
        <li>One</li>
        <li>Two</li>
        <li>Three</li>
    </ul>
</div>

CSS:

div {width: 100%}
ul {
    border: dashed 1px rgb(0,0,100);
    list-style: none;
    padding-left: 0;
}
ul > li {
    background-color:#cccccc;
    border-bottom:1px solid white;
    border-top:1px solid white;
    padding: 1% 0;
}

jsFiddle: http://jsfiddle.net/uqkhcktj/

With The Desired Effect, but Without Using A Set Width http://jsfiddle.net/uqkhcktj/2/

3 个答案:

答案 0 :(得分:3)

What you really want is to center the container of the list without an absolute width (should automatically fits the list width);

Just set your container's width to auto and use display:inline-block; so the container can grow as much as needed. After that just center the container within the parent, and force the list text-align to left so it doesn't inherit the centralized alignment from it's parent.

http://jsfiddle.net/uqkhcktj/5/

div#parent {
    text-align:center;
}
div#container {
    display:inline-block;
    width: auto;
}
ul {
    text-align:left;
    border: dashed 1px rgb(0,0,100);
    list-style: none;
    padding-left: 0;
}

答案 1 :(得分:1)

I'm not sure if you need the li to be any specific width, but a way to do this would be with margin:auto

fiddle: http://jsfiddle.net/uqkhcktj/3/

html

<div>
    <ul>
        <li>One</li>
        <li>Two</li>
        <li>Three</li>
    </ul>
</div>

css

div {width: 100%}
div li
{
    width:50%;
    margin:auto;
}
ul {
    border: dashed 1px rgb(0,0,100);
    list-style: none;
    padding-left: 0;
}
ul > li {
    background-color:#cccccc;
    border-bottom:1px solid white;
    border-top:1px solid white;
    padding: 1% 0;
}

答案 2 :(得分:0)

If you're wanting something like that and to still retain the full width look you could add a span to the html so you can center the words specifically. You need to set a width and do margin:0 auto to center them.

Js Fiddle: https://jsfiddle.net/7mgp4srk/1/

Html:

<div>
    <ul>
        <li><span>One</span></li>
        <li><span>Two</span></li>
        <li><span>Three</span></li>
    </ul>
</div>

Css:

div {width: 100%}
ul {
    border: dashed 1px rgb(0,0,100);
    list-style: none;
    padding-left: 0;
}
ul > li {
    background-color:#cccccc;
    border-bottom:1px solid white;
    border-top:1px solid white;
    padding: 1% 0;
}

ul > li span {
    width:20%;
    margin:0 auto; 
    display:block;
}