html - 水平对齐 div 与额外的 margin-left 和 margin-right

标签 html css

我想居中 <div /><body />并添加额外的 margin-leftmargin-right
类似的东西 - 当然应该有效:) https://jsfiddle.net/kweyn912/

通常,我会使用 margin: auto ,但在这种情况下,我想特别添加额外的 margin ,所以我不能那样做。

我尝试使用 transform: translateX(-50%)连同 left: 50%margin-left .在我尝试设置 margin-right 之前一直有效

旁注:
我有一些限制:我不能使用 padding而不是 margin .我不能使用 position: absolute我必须使用 display: block

最佳答案

更新您的元素添加

div {
  width: 200px;
  height: 100px;
  background: lightblue;
  margin-left: 20px;
  margin-right: 40px;
  position: absolute;
  left: calc(50% - 110px)
}

body {
  width: 100%;
  background: white;
  text-align: center
}

https://jsfiddle.net/kweyn912/6/

关于html - 水平对齐 div 与额外的 margin-left 和 margin-right,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35585485/

相关文章:

html - 为 TextField 中的占位符设置样式

html - 居中对齐div

java - 如何在 J2EE 元素中使用 javafx 应用程序而不是 html 页面?

javascript - SVG Sprite 模式在 D3 中不起作用

php - 嵌套选择器无法使用简单的 html dom 解析器

javascript - node.js 从 html 输入值

html - 无法从互联网链接样式表

html-pdf 文本对齐 : justify not working?

html - 水平滚动条宽度

android - Android 版 Chrome 中的网站文字更大