开发者

Centering a specific element inside a div using CSS?

开发者 https://www.devze.com 2022-12-15 02:29 出处:网络
I have some html that looks like this <div id=\'nav\'><a href =\'./?page=1\'>1</a> 2 <a href =\'./?page=3\'>3</a> <a href =\'./?page=4\'>4</a> <a href =\'

I have some html that looks like this

<div id='nav'><a href ='./?page=1'>1</a> 2 <a href ='./?page=3'>3</a> <a href ='./?page=4'>4</a> <a href ='./?page=5'>5</a></div>

Basically, this is a navigation menu where the current page is 2. Now, the problem is, I want the current page (2 in this case) to always be centered. I'm just using text-align:center but this just means that 3 is always in the center. How do I make it so that the current page number is always in the center, regardless of whether it is the middle element in the list of links?

EDIT:

Ok, to be a little more clear, in the above case I want to look like this

 1 2 3 4 5
   ^
   |
  This should be centered in the page and the spacing between the others
  should remain the same. So the links will actually be slightly offcenter to
  the right, but the current page will be in the ce开发者_运维技巧nter of the page.


I think I see what you're trying to do. Seems it should be pretty straightforward, but isn't. I think you might need to resort to absolute positioning and calculating the precise values on the server (or in javascript on the client). I also think that you'll need a container for the non-linked element. Something like this:

<style type="text/css>
 #nav {position: relative}
 #nav ol {list-style: none; margin: 0; padding: 0}
 #nav ol li {display: block; margin: 0; padding: 0; position: absolute; width: 10%; text-align: center}
 #nav ol li a {}
</style>

<div id="nav">
 <ol>
  <li style="left: 35%" ><a href="?p=1">1</a></li>
  <li style="left: 45%" >2</li>
  <li style="left: 55%" ><a href="?p=1">3</a></li>
  <li style="left: 65%" ><a href="?p=1">4</a></li>
  <li style="left: 75%" ><a href="?p=1">5</a></li>
 </ol>
</div>


EDIT: To answer your revised question:

I would use markup like this

<div id="#nav">
    <div>
        <span class="spacer"></span>
        <a href ='./?page=1'>1</a> 
        2 
        <a href ='./?page=3'>3</a> 
        <a href ='./?page=4'>4</a> 
        <a href ='./?page=5'>5</a>
    </div>
</div>

And then css (with widths calculated appropriately):

#nav div
{
    margin:0 auto;
    /* width: 9 * link width */
}
#nav div .spacer
{
    display:inline-block;
    /* width: 3 * link width */
}


Perhaps something like this. If the width is not fixed then I think you'll need to use Javascript to do the ol margin-left calculation.

ol
{
    display: block;
     height: 20px;
     margin-left: 0;
}

ol li
{
     float: left;
     width: 20px;
     height: 20px;

}

body#page2 ol
{
    margin-left: 300px;  /*calculate this by hand or use jQuery to do the math*/

}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号