html - 如何使用CSS水平居中div和span元素

标签 html css center

这是 JS Fiddle 的链接:JS Fiddle

我试图让我的边框和图标水平位于页面的中心。使用背景色 #f30

但是一切似乎都停留在左侧。我在这里尝试了几篇文章,但它们似乎没有用,还检查了 Google 以获取更多信息,但似乎没有任何解决办法。

这是供您检查的 HTML:

<div id ="heading_layout" class="section-1">
<span class="d"><span class="icon"></span></span>
</div>

这是供您检查的 CSS:

#heading_layout {
 margin-top: 30px;
  width: 100%;
  text-align: center;
  background: #f30;
}

.section-1 span.d:before {
  float: left;
  content: '';
  width: 10%;
  height: 1px;
  border-bottom: 2px dashed #8000ae;
}

.section-1 span.d:after {
  position: relative;
  right: 0px;
  float: left;
  top: 100%;
  content: '';
  width: 10%;
  height: 1px;
  border-bottom: 2px dashed #8000ae;
}

span.icon {
    position: relative;
    margin-left: 15px;
    margin-right: 15px;
    margin-top: -14px;
    height: 30px;
    width: 30px;
    border-radius: 50%;
    float: left;
    background: 
    #8000ae url('') 
    3px 3px no-repeat; 
}

这是 JS Fiddle 的链接:JS Fiddle

谢谢。

最佳答案

我重新编辑了你的 CSS:

#heading_layout {
  margin-top: 30px;
  width: 100%;
  text-align: center;
  background: #f30;
}

.section-1 span.d:before {
  display: inline-block;
  content: '';
  width: 10%;
  height: 1px;
  border-bottom: 2px dashed #8000ae;
  margin-bottom: 12px;
}

.section-1 span.d:after {
  position: relative;
  right: 0px;
  display: inline-block;
  top: 100%;
  content: '';
  width: 10%;
  height: 1px;
  border-bottom: 2px dashed #8000ae;
  margin-bottom: 12px;
}

span.icon {
    position: relative;
    margin-left: 15px;
    margin-right: 15px;
    height: 30px;
    width: 30px;
    border-radius: 50%;
    display: inline-block;
    background: 
    #8000ae url('') 
    3px 3px no-repeat; 
    margin-top: 5px;
}

我做了什么:

  1. 将“float: left”替换为“display: inline-block”——现在文本对齐实际上影响了它们。
  2. 删除了不必要的负边距

就这些。希望我说清楚了。

关于html - 如何使用CSS水平居中div和span元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26929664/

相关文章:

html - 为什么第 nth-of-type/nth-child 不适用于嵌套元素?

javascript - 密码请求窗口不会在屏幕上居中 :(

html - 如何使用 'aside' 标签使垂直图像居中?

javascript - jQuery 工具 : Scrollable/Navigator items flowing out of the container

javascript - Canvas 文本调整大小

javascript - Google map 仅在 iPad 上导致不可见的 html 元素,为什么会出现奇怪的行为?

javascript - 查找是否在父 div 中选中了所有复选框

html - 鼠标悬停之前文本模糊?

css - CSS 动画 rotateZ 的 Opera 问题

html - 定位垂直中心