我有一个无序列表,其中包含多个列表元素。里面还有一个要居中的图像元素。我尝试使用 margin: auto; 将它居中。属性,但由于侧面有列表元素,因此在居中时会考虑到这一点。如何使图像相对于它的容器居中?
.nav {
width: 1280px;
margin: 0 auto;
font-size: 16px;
font-weight: 500;
border: 1px solid black;
}
.nav li {
float: left;
vertical-align: top;
margin: 5px 10px;
}
nav li:first-child {
margin-left: 75px;
}
.nav img {
display: block;
margin: auto;
height: 21px;
width: 24px;
}
<nav class="nav">
<ul class="clearfix">
<li>Home</li>
<li>Moments</li>
<li>Notifications</li>
<li>Messages</li>
<img src="assets/image/twitter-icon.png" alt="Twitter Icon">
</ul>
</nav>
最佳答案
您可能必须使用以下方法将图像 absolute
定位到 nav
元素中:
position: absolute;
left: 50%;
transform: translateX(-50%);
还有 position:relative
nav
元素。
这样图像会忽略 nav
元素中的任何内容。
body{
margin:0px;
}
.nav {
width: 1280px;
margin: 0 auto;
font-size: 16px;
font-weight: 500;
border: 1px solid black;
position:relative;
}
.nav li {
vertical-align: top;
margin: 5px 10px;
display: inline;
}
nav li:first-child {
margin-left: 75px;
}
.nav img {
position: absolute;
left: 50%;
transform: translateX(-50%);
height: 21px;
width: 24px;
}
<nav class="nav">
<ul class="clearfix">
<li>Home</li>
<li>Moments</li>
<li>Notifications</li>
<li>Messages</li>
<img src="assets/image/twitter-icon.png" alt="Twitter Icon">
</ul>
</nav>
关于html - 如何将图像与其他元素放在列表中居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44403934/