html - flex-grow automatic margin for the first element
问题描述
Let's say I have navigation that uses two flexbox containers. With flex-grow property, navigation stretches to fit the main wrapper (which is of 100% width in this case).
HTML:
<!DOCTYPE html>
<html lang="en">
<body>
<div id="main_navigator">
<a id="main_navigator_logo" src="/"></a>
<ul id="main_navigator_r1">
<li>
<a class="main_nav_btn">BTN 1</a>
</li>
<li>
<a class="main_nav_btn">BTN 2</a>
</li>
<li>
<a class="main_nav_btn">BTN 3</a>
</li>
<li>
<a class="main_nav_btn">BTN 4</a>
</li>
<li>
<div id="main_navigator_s1"></div>
</li>
<li>
<div id="main_navigator_regbox"></div>
</li>
</ul>
</div>
</body>
</html>
CSS:
body {
margin: 0;
}
#main_navigator {
position: fixed;
display: flex;
flex-direction: row;
background-color: black;
width: 100%;
}
#main_navigator_logo {
width: 416px;
height: 120px;
display: block;
background-color: white;
}
#main_navigator_r1 {
display: flex;
flex-direction: row;
align-items: center;
flex-grow: 1;
flex-shrink: 1;
margin-top: 0px;
height: 96px;
list-style-type: none;
}
#main_navigator_r1 li {
flex-grow: 1;
flex-shrink: 1;
}
#main_navigator_r1 li .main_nav_btn {
color: white;
display: block;
height: 100%;
font-family: "nexa_bold";
font-size: 0.8em;
text-decoration: none;
}
#main_navigator_s1 {
width: 2px;
height: 30px;
background-color: #B28039;
}
#main_navigator_regbox {
background-color: red;
width: 50px;
height: 5px;
}
As you can see from the code, there is a main container with flexbox property that contains a logo (<a>
element) and navigation (<ul>
element that contains flexbox property).
It can be seen that left margin of the first element remains constantly fixed, so margin (or padding) between logo and element remains the same regardless of scaling, whereas other margins between navigation elements are increasing along with viewport when positively scaled.
You can view the visualization here.
Is it possible to make all elements in navigation to have same automatic margin?
I've tried putting the logo in <ul>
container - but due to some automatic resizing it disappeared (the size of logo should remain static, but right margin should not). Is it possible to wrap logo in the container in this specific way?
Thank you!
解决方案
要为第一个元素添加自动边距,导航器不能有预设的填充,并且必须将其内联元素居中。在这种情况下:
#main_navigator_r1 {
padding:0;
text-align:center
}
为了保持这些列表元素之间的相同差异,它们必须都具有相同的显示属性,在这种情况下display: inline-block
:
#main_navigator_r1 li {
display: inline-block;
}
flex-basis
也可以为具有 flexbox 显示属性的父元素的元素考虑 property - 如果flex-basis
property 设置为0
,则 flexbox 容器内的所有元素将具有相等的宽度 - 因此它们之间的间距相等。
推荐阅读
- python - 在 Raspbian os 中使用 playsound 模块时出现“命名空间 Gst 不可用”错误
- charts - 散景垂直条形图
- node.js - mongodb mongoose如何理解给定的id在填充的ref中找不到
- python - 如何根据一列对df进行分组并将函数应用于熊猫中的另一列
- python - python中Sqlite的NULL值
- python - 使用 django.test.client.post 时出现错误请求
- c++ - 如何使用构成排序键的位域而不落入UB?
- android - 将不同的依赖 LiveData 对象合并为一个
- python - 如何在 O(1) 中按键列选择行?(Python 数据表)
- php - 在wordpress中提交表单响应后在后台运行功能