html – CSS:如何在居中元素周围对齐元素?

我正在尝试创建一个由三部分组成的简单页面导航:

>几个以前的页码(如果有的话)
>当前页码(必须居中)
>一些即将到来的页码(如果有的话)

重要的是当前页码始终在父容器中水平居中.其他两个部分应均匀占据剩余的水平空间.

这个JSFiddle说明了我解决这个问题的两次尝试.

解决方案1:使用text-align:center.这实现了期望的结果,但仅在两侧宽度相等的情况下.如果不是,则当前页码不在中心.

HTML

<div class="container">
  <input type="button" value="47">
  <input type="button" value="48">
  <input type="button" value="49">
  <input type="text" size="5" maxlength="5" value="50">
  <input type="button" value="51">
  <input type="button" value="52">
  <input type="button" value="53">
</div>

CSS

.container,input {
    text-align: center;
}

解决方案2:使用手动指定的宽度均匀分布水平空间.这有效地将当前页码的中心置于所有情况下,但它需要您对宽度进行硬编码.

HTML

<div class="container">
  <div class="left">
      <input type="button" value="47">
      <input type="button" value="48">
      <input type="button" value="49">
  </div>
  <div class="right">
      <input type="button" value="51">
      <input type="button" value="52">
      <input type="button" value="53">
  </div>
  <div class="center">
      <input type="text" size="5" maxlength="5" value="50">
  </div>
</div>

CSS

.left {
    width: 40%;
    float: left;
    text-align: right;
}
.right {
    width: 40%;
    float: right;
    text-align: left;
}
.center {
    width: 20%;
    margin-left: 40%;
}

这些解决方案都没有真正做到我想要的.有没有办法让当前页码居中,同时允许其他元素与其自然大小对齐,而不是任意像素或百分比宽度?

解决方法

你应该使用 flex和浮动属性,检查我的解决方案:
.container {
  display: -webkit-flex; /* Safari */
  display: flex;  
}

.container,input {
    text-align: center;
}

.container:after {
    content:"";
    position: absolute;
    z-index: -1;
    top: 0;
    bottom: 0;
    left: 50%;
    border-left: 2px dotted #ff0000;
}

.left {
  display: inline-block;
  flex: 1;
  
}

.left input {
  float: right;  
}

.right {
  display: inline-block;
  flex: 1;
}

.right input {
  float: left;
}

.center {
  display: inline-block;
}
<div class="container">
  <div class="left">
      <input type="button" value="48">
      <input type="button" value="49">
  </div>
  <div class="center">
      <input type="text" size="5" maxlength="5" value="50">
  </div>
  <div class="right">
      <input type="button" value="51">
      <input type="button" value="52">
      <input type="button" value="53">
  </div>
  
</div>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Mip是什么意思以及作用有哪些
怎么测试Mip页面运行情况
MIP安装的具体步骤有哪些
HTML添加超链接、锚点的方法及作用详解(附视频)
MIP的规则有哪些
Mip轮播图组件中的重要属性讲解
Mip的内联框架组件是什么
怎么创建初始的MIP配置及模板文件
HTML实现多选框及无法提交多数据的原因分析(附视频)
HTML如何设置复选框、单选框以及默认选项?(图文+视频)
怎么使用MIP组件
Div垂直居中效果怎么实现
HTML如何实现视频在线播放
如何使用Mip代码校验工具
Mip中弹出层组件是什么
如何用HTML实现简单按钮样式
Mip中快速回顶组件怎么用
Div内容居中效果如何实现
Div水平居中效果怎么实现
Mip中列表组件怎么用