具有 margin-auto 属性的图像不会在其具有 display flex 属性的父级中垂直和水平居中。此问题仅在 chrome 上普遍存在。我已经在 Brave(我的主要浏览器)、Firefox 和 Microsoft Edge 上对此进行了测试。
截取 Brave 和 Chrome 的屏幕截图,向您展示问题所在以及应该是什么样子 勇敢(它应该是什么样子):http://prntscr.com/nn8zeu Chrome :http://prntscr.com/nn8zp3
我正在使用 Bootstrap ,所以对于那些不熟悉类名的人来说。
m-auto = 边距:自动
d-flex = 显示:flex
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- jQuery -->
<script src="./node_modules/jquery/dist/jquery.js"></script>
<!-- Bootstrap -->
<link rel="stylesheet" href="./node_modules/bootstrap/dist/css/bootstrap.css">
<title>Document</title>
</head>
<body>
<div class="container mt-4">
<h1 class="mb-1">Hi Stackoverflow</h1>
<p>The item below is div with display flex and some styles to make it round and look pretty. <br> The image inside has margin-auto. Why does image <b>Not</b> center on chrome?. pls help</p>
<div class="d-flex align-items-center">
<div class="icon mr-2 d-flex">
<img src="https://img.icons8.com/ios/420/discord-logo.png" alt="" class="img m-auto">
</div>
</div>
</div>
</body>
</html>
<style>
.icon {
width: 50px;
height: 50px;
border-radius: 50%;
background-color: lightseagreen;
}
.img {
width: 25px;
height: auto;
filter: invert(100%);
}
</style>
最佳答案
下面是一个在 .icon
类 div 中将图像居中的示例,方法是将显示设置为 flex,并将所有内容对齐并对齐到中心。我在 css 中的 .icon
选择器的顶部添加了 4 行代码。
.icon {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
width: 50px;
height: 50px;
border-radius: 50%;
background-color: lightseagreen;
}
.img {
width: 25px;
height: auto;
filter: invert(100%);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- jQuery -->
<script src="./node_modules/jquery/dist/jquery.js"></script>
<!-- Bootstrap -->
<link rel="stylesheet" href="./node_modules/bootstrap/dist/css/bootstrap.css">
<title>Document</title>
</head>
<body>
<div class="container mt-4">
<h1 class="mb-1">Hi Stackoverflow</h1>
<p>The item below is div with display flex and some styles to make it round and look pretty. <br> The image inside has margin-auto. Why does image <b>Not</b> center on chrome?. pls help</p>
<div class="d-flex">
<div class="icon mr-2 d-flex">
<img src="https://img.icons8.com/ios/420/discord-logo.png" alt="" class="img m-auto">
</div>
</div>
</div>
</body>
</html>
希望对您有所帮助!祝你有美好的一天:)
关于html - 带有 margin auto 的元素不会在 chrome 中显示 flex 的父元素内部居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56092274/