【问题标题】:How can you define the width of a container in % relatively to an element that is NOT its direct parent?相对于不是其直接父元素的元素,如何以 % 为单位定义容器的宽度?
【发布时间】:2019-11-22 22:50:11
【问题描述】:

我的标题如下:logo + nav 包含 4 个链接 我想将所有这些元素在顶部彼此相邻排列(这是有效的),但也要使它们彼此等距。第二部分不起作用,我无法在 % 中定义 a 元素的大小 ...

我正在使用 float:left 将所有这些元素放在彼此相邻的顶部。我正在使用 css 属性宽度使它们占据页面总顶部的 20%。

<body>
    <header>
      <a href="./index.html" class="logo"><img src="mylogo.png" style="width:42px;height:42px"></a>
      <nav>
        <a href="./index.html" class="welcome active">Welcome</a>
        <a href="./about.html" class="about">About</a>
        <a href="./artwork.html" class="artwork">Art Work</a>
        <a href="./events.html" class="events">Events</a>
       </nav>
     </header>
     <h1>Title of the page</h1>
</body>
* {
    box-sizing: border-box;
    padding: 0px;
    margin: 0px;
}

header {
    width: 100%;
}

.logo {
    float: left;
    width: 20%;
}

nav {
    float: left;
}

nav a {
    width: 20%;
}

标志和链接之间有一些空间,但链接并没有沿着顶部等距离排列,它们彼此粘在一起......我想这是因为它们的宽度是相对于导航的,而不是100% 因为有标志。但是我不知道如何定义这些 a 元素相对于我固定为页面 100% 的标题的大小?

【问题讨论】:

  • 制作nav的宽度80%

标签: css css-float width


【解决方案1】:

这是我的解决方案。我对您的 css 进行了一些更改,而不是浮动,我使用 flex-box 技术来对齐它们。我将标题设为黑色以轻松检测标题。您可以在 css 中更改它。希望此解决方案对您有所帮助。

* {
    box-sizing: border-box;
    padding: 0px;
    margin: 0px;
}

header {
    height: 10vw;
    line-height: 10vw;
    width: 100%;
    background-color: #000;
}

.logo img {
    vertical-align: middle;
}

a {
    display: inline-block;
    height: inherit;
    width: 20%;
    text-align: center;
    line-height: inherit;
    vertical-align: bottom;
    transition: all .33s ease-in-out;
}

a:hover {
    background-color: white;
}
<body>
    <header>
      <a href="./index.html" class="logo"><img src="mylogo.png" style="width:42px;height:42px"></a><!-- --><a href="./index.html" class="welcome active">Welcome</a><!-- --><a href="./about.html" class="about">About</a><!-- --><a href="./artwork.html" class="artwork">Art Work</a><!-- --><a href="./events.html" class="events">Events</a>
       
     </header>
     <h1>Title of the page</h1>
</body>

【讨论】:

  • 谢谢@Showrin Barua,这不是我想要的,因为元素之间的距离仍然不相等(徽标和链接之间的空间更大),但我会调查这个显示:flex,它似乎可能导致解决方案。
  • @JääßJääß 欢迎。但我还是不明白你想要什么('_')。
  • 那个logo,和每个链接都在上面等距离。假设 -- 等于 40px: 浏览器左侧边框 I -- Logo -- 欢迎 -- 关于 -- 艺术作品 -- 事件 -- I 浏览器右侧边框
  • 也许我已经理解了。我刚刚在我的答案中做了另一个编辑。请检查一下。
  • 不,实际上我想要这样的东西:w3schools.com/howto/howto_css_topnav_equal_width.asp 但问题是当我添加徽标时它不起作用,我必须设置我假设的宽度错误,或者可能是事实听者中有一个 a + nav a 打破它
【解决方案2】:

我发现以下 CSS 有效:

header {
    width: 100%;
    display: inline-block;
}

.logo {
    float: left;
    width: 20%;
}

header nav {
    width: 80%;
    float: left;
}

header nav a {
    width: 20%;
    float: left;
    text-align: center;
}

【讨论】:

    猜你喜欢
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-11
    • 2013-05-29
    • 1970-01-01
    • 2012-12-16
    相关资源
    最近更新 更多