.flex-container { display: flex; /* displays flex-items (children) inline */ justify-content: center; /* centers them horizontally */ position: relative;}.flex-container > div { width: 100px; height: 100px;}#left { background: #009a9a;}#right { position: absolute; left: 50%; /* moved right by half of the parent's width */ transform: translateX(50%); /* and half of its own width */ background: #bbad4f;} <div class="flex-container"> <div id="left"></div> <div id="right"></div></div>无论 divs宽度(只要它们保持不变),此解决方案都是 dynamic ,因此没有不必要的 margins 或 calc().但是借助 CSS变量 ,您可以使其完全 dynamic : :root { --leftWidth: 200px;}.flex-container { display: flex; justify-content: center; position: relative;}.flex-container > div { width: 100px; height: 100px;}#left { width: var(--leftWidth); background: #009a9a;}#right { position: absolute; left: calc(50% + (var(--leftWidth)/2)); /* moved right by half of the parent's and sibling's width */ background: #bbad4f;} <div class="flex-container"> <div id="left"></div> <div id="right"></div></div>I'm trying to make a centered div with another div on the right of it. So the div on the left is horizontal centered. De div on the right is directly on the right of the centered div. I've tried it in many ways with different displays and margins etc but I can't seem to figure it out.All tips are welcome!div { width: 100px; height: 100px; display: inline-block;}#left { left: 50%; background: #009a9a;}#right { background: #bbad4f;}<div id="left"></div><div id="right"></div> 解决方案 You can do it with the Flexbox and positioning:.flex-container { display: flex; /* displays flex-items (children) inline */ justify-content: center; /* centers them horizontally */ position: relative;}.flex-container > div { width: 100px; height: 100px;}#left { background: #009a9a;}#right { position: absolute; left: 50%; /* moved right by half of the parent's width */ transform: translateX(50%); /* and half of its own width */ background: #bbad4f;}<div class="flex-container"> <div id="left"></div> <div id="right"></div></div>No matter the divs width (as long as they stay the same), this solution is dynamic, therefore no unnecessary margins or calc().But with the help of CSS variables you can make it completely dynamic::root { --leftWidth: 200px;}.flex-container { display: flex; justify-content: center; position: relative;}.flex-container > div { width: 100px; height: 100px;}#left { width: var(--leftWidth); background: #009a9a;}#right { position: absolute; left: calc(50% + (var(--leftWidth)/2)); /* moved right by half of the parent's and sibling's width */ background: #bbad4f;}<div class="flex-container"> <div id="left"></div> <div id="right"></div></div> 这篇关于如何获得一个以另一个div为中心的div?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
07-22 08:16