代码之家  ›  专栏  ›  技术社区  ›  JerSchneid

使用CSS创建占用父对象整个宽度的多个元素

  •  3
  • JerSchneid  · 技术社区  · 15 年前

    我试图实现一个水平CSS菜单栏,其中所有 <a> 组合的元素将扩展到父元素的整个宽度。HTML的外观如下所示:

    <div id="parent">
        <a href="/">Home</a>
        <a href="/learn">Learn More About The Product</a>
        <a href="/about">About Us</a>
        <a href="/contact">Contact Us</a>
    </div>
    

    这四个概念各有不同 < Home Contact Us 与边缘对齐 parent

    有什么想法吗?

    3 回复  |  直到 10 年前
        1
  •  2
  •   VoteyDisciple    15 年前

    <div id="parent">
        <a href="/" style="width: 20%;">Home</a>
        <a href="/learn" style="width: 40%;">Learn More About The Product</a>
        <a href="/about" style="width: 20%;">About Us</a>
        <a href="/contact" style="width: 20%;">Contact Us</a>
    </div>
    
        2
  •  2
  •   Mailo Světel    15 年前

    您可以一起计算字符串的长度,然后通过特定的字符串长度得到整个菜单的百分比部分。

    <?php
    // percentageCounter.php
    $menuItems = array(
     'home'=>array('label'=>'Home'),
     'learn'=>array('label'=>'Learn More About The Product',),
     'about'=>array('label'=>'About Us',),
     'contact'=>array('label'=>'Contact Us',),
     'str_len_sum' => 0,
    );
    foreach($menuItems AS $key => $menuItem)
    {
      $menuItems['str_len_sum'] += strlen($menuItem['label']);
    }
    
    foreach($menuItems AS $key => $menuItem)
    {
      $menuItems[$key]['percentage'] = (100/$menuItems['str_len_sum'])*strlen($menuItem['label']);
    }
    

    还有一个是打印菜单

    <?php //menuOutput.php
    require_once 'percentageCounter.php';
    ?>
    <div id="parent">
    <?php foreach($menuItems AS $key => $menuItem): ?>
        <a href="/<?php echo $key ?>" style="width: <?php echo $menuItem['percentage'] ?>%;"><?php echo $menuItem['label'] ?></a>
    <?php endif; ?>
    </div>
    
        3
  •  0
  •   jeroen    15 年前

    我想这取决于需求(IE6…),但您可以尝试使用:

    #parent {
        display: table-row;
    }
    #parent a {
        display: table-cell;
    }
    

    我还没有试过,但我认为这应该会让它有一种餐桌式的行为。