html - 将我们的元素分布在父宽度上

标签 html css

我试图在屏幕宽度上展开 3 个元素。我尝试了不同的方法,但是当我使用 inline-block 时,第二个元素没有居中。当我省略 inline-block 时,第三个元素显示在下一行。有什么建议吗?

<html>
<head>
    <style>
        * {
            margin: 0px;
            padding: 0px;
        }
        .base {
            display: block;
            height: 200px;
            background-color: #eeeeee;
        }
        .container {
        }
        .shape {
            width: 100px;
            height: 100px;
            background-color: #ff0000;
        }
        .container {
        }
        #left {
            float: left;
        }
        #center {
            margin: auto;
        }
        #right {
            float: right;
        }
    </style>
</head>
<body>
    <div class="base">
        <div class="container">
            <div class="shape" id="left"></div>
            <div class="shape" id="center"></div>
            <div class="shape" id="right"></div>
        </div>
    </div>
</body>
</html>

最佳答案

您可以使用以下 CSS3 来执行此操作。

* {
            margin: 0px;
            padding: 0px;
        }
        .base {
            display: block;
            height: 200px;
            background-color: #eeeeee;
        }
        .container {
        }
        .shape {
            width: 100px;
            height: 100px;
            background-color: #ff0000;
        }
        .container {
        display:flex;
        justify-content:space-between;
        }
<div class="base">
        <div class="container">
            <div class="shape" id="left"></div>
            <div class="shape" id="center"></div>
            <div class="shape" id="right"></div>
        </div>
    </div>

CSS 解决方案

* {
            margin: 0px;
            padding: 0px;
        }
        .base {
            display: block;
            height: 200px;
            background-color: #eeeeee;
        }
        .container {
        }
        .shape {
            width: 100px;
            height: 100px;
            background-color: #ff0000;
        }
        .container {
          display:block;
          text-align:center;
        }
        #left{
          float:left;
        }
        #right{
          float:right;
        }
        #center{
          display:inline-block;
        }
<div class="base">
        <div class="container">
            <div class="shape" id="left"></div>
            <div class="shape" id="center"></div>
            <div class="shape" id="right"></div>
        </div>
    </div>

关于html - 将我们的元素分布在父宽度上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45904310/

相关文章:

javascript - 需要测验应用程序一次只显示一个项目

javascript - 私有(private)菜单,大小灵活

javascript - 单击移动设备(汉堡菜单)时为整个 Bootstrap 菜单栏着色

html - Display Tag 是否与 IE 9 兼容?

javascript - 如何循环图像

html - span inside anchor 不起作用,有什么想法吗?

javascript - 如何更新标记的信息窗口?

html - 在 div 顶部修剪一个小的空三 Angular 形

html - 如何显示html div,以便在表单提交后自动显示错误消息

javascript - 在 HTML 中使用 Canvas 时不显示文本