如何在一个 div(nav) 中有不同的对齐方式?

How to have different alignments in one div(nav)?

在此fiddle中:https://jsfiddle.net/vtrec4oL/

我希望 #leftSide 在我的 <nav> 的左端对齐,其余的在中间。

但我希望我的页面尽可能兼容 window 调整大小,所以我不想使用 margin/padding。

此外,如果可能的话,我很乐意在没有其他元素的情况下实现这一目标。

有谁知道如何仅使用 css 来做到这一点?

如果要对齐特定元素,只需创建一个 class 并将其添加到该元素即可。 如果您想对齐最后 child 或第一个 child,请在 css 中使用 :first-child 或 :last-child 选择器。 请记住 #leftSide 是一个 ID,do 将影响一个元素,而不是使用 class.

将以下内容添加到您的 css 中:

#leftSide{
    float:left;
}

但是,如果我是你;我会为左边的图片添加几个像素的边距,这样它就不会在边缘。

不幸的是,我的解决方案稍微破坏了您的垂直对齐!

I want a#gnbii to align on the left end of my nav bar and the rest of the links in the center.

But I want my page to be as compatible as possible to window resizing so I prefer not to use margin/padding.

Also I would love to achieve this with no additional element if possible.

结合使用 CSS flexboxpositioning 属性可以满足所有要求。

首先,为您的 a#gnbii 父容器添加一个 ID:

<li class="gnb" id="align-left"> /* NEW - ID added */
<a class="gnb" id="gnbii" href="home.html">
<img id="gnbii" src="../images/instagram icon/1.png" alt="aranpuzzle.ir" height="40px">
<img id="gnbii" src="../images/instagram icon/2.png" alt="aranpuzzle.ir" height="40px">
</a>
</li>

这是 CSS:

ul {
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
}

#align-left {
    position: absolute;
    left: 2%;
}

演示:https://jsfiddle.net/6pmfc87h/3/

事情是这样的...

  • ul 成为应用了 display: flex 的 flexbox。每个 li 现在排成一行,这是 flexbox 子项的默认行为(称为 "flex items")。

  • justify-content: center 子元素沿主轴居中。在这种情况下,水平。

  • align-items: center 子元素沿横轴居中。在这种情况下,垂直。

  • position: relative为绝对定位建立最近的定位祖先

  • position: absolute 将最后一个 li 移动到其最近定位祖先的左边缘。

要了解更多关于 flexbox 的信息,这里有一个很好的参考:A Complete Guide to Flexbox

要了解有关绝对位置的更多信息,请查看:MDN position


更新(基于评论;适用于较小的屏幕)

i want it to slide to right as much as possible instead of overlapping...

好的,所以我们可以将 white-space: nowrap 添加到 ul,以便导航项始终保持在一行中。

然后声明一个媒体查询以在较小的屏幕上将所有内容向右移动:

@media only screen and (max-width: 768px) { 
    ul { justify-content: flex-start; }  /* note: site is RTL */
    #align-left { position: static; }
}

更新的演示:https://jsfiddle.net/6pmfc87h/4/

...and when there is no more space to slide right, i prefer that then the explorer doesn't let the user resize the width of the window any thiner!

您确定这是您要执行的操作吗?有some JavaScript methods that set browser window size, but I'm not sure they're completely reliable across all browsers. More importantly, I don't think this adheres to best practices. In my view, a user should be allowed to re-size their browser window however much the browser natively allows. [Learn more.]

作为 Web 开发人员,您最好专注于您拥有更多控制权的领域。您可以设置一个 min-width 声明,告诉浏览器您的元素不能再变窄了。或者您可以使用媒体查询来更改周围的内容以适应较小的屏幕。