【问题标题】:How to make 3 text boxes on the same line and center aligned如何使3个文本框在同一行并居中对齐
【发布时间】:2015-05-05 21:36:54
【问题描述】:

我想要 3 个文本框沿水平轴左、中、右对齐,并且在同一行上。

我可以使用margin-leftmargin-right在中间设置一个文本框,然后使用position:absoluteleft:0我可以在左侧获得一个文本框(在同一行作为中间框)。

现在的问题是最后一个盒子,右边的盒子。使用position:absoluteright:0,将框定位在右侧,但在下方显示一行。

我不知道我做错了什么,老实说,我不知道position:absoluteleft:0 是如何使元素与中间元素出现在同一行的。

#sectionM,
#sectionL,
#sectionR {
  width: 250px;
  border: 1px outset black;
  padding: 5%;
  text-align: center;
}
#sectionM {
  margin-left: auto;
  margin-right: auto;
}
#sectionL {
  position: absolute;
  left: 0px;
}
#sectionR {
  position: absolute;
  right: 0px;
}
header {
  text-align: center;
}
nav {
  text-align: center;
}
<!DOCTYPE html>
<html lang="en-US">

<head>
  <meta charset="UTF-8">
  <title>Misha's Homepage</title>
  <link rel="stylesheet" type="text/css" href="mainstyle.css">
</head>

<header>
  <h1>Hi!</h1>
</header>

<nav><a href="archive/myFirstWebpage/mainPage.html">Archive</a>
</nav>

<article>
  <section id="sectionL">
    This is the left LEFT.
  </section>

  <section id="sectionM">
    This is the mid MID.
  </section>

  <section id="sectionR">
    This is the right RIGHT.
  </section>
</article>

</html>

【问题讨论】:

    标签: html css


    【解决方案1】:

    有很多方法可以做到这一点。这是使用inline-block 的解决方案,因为它响应迅速并且几乎适用于所有浏览器。

    http://jsfiddle.net/kop21mbg/

    body {
        text-align: center;
    }
    nav {
        margin-bottom: 1.5em;
    }
    article {
        font-size: 0; /*fix white space*/
    }
    article > section {
        font-size: 16px;
        display: inline-block;
        width: 250px;
        border: 1px outset black;
        padding: 30px;
        box-sizing: border-box;
    }
    <header>
         <h1>Hi!</h1>
    </header>
    <nav>
        <a href="#">Nav item</a>
    </nav>
    <article>
        <section>This is the left box.</section>
        <section>This is the mid box.</section>
        <section>This is the right box.</section>
    </article>

    如果您不希望它具有响应性,请添加以下样式。

    article {
        width: 750px;
    }
    

    【讨论】:

    • 感谢您的回复,但我对您的示例感到有些困惑。在您的示例 html 中,您仍在使用 id="sectionL" 等,但在您的示例 CSS 中,您没有这些 id。所以我没有看到这是如何工作的。我唯一能想到的是,即使 CSS 中没有 id,html 代码也可以使用它所拥有的(在文章 > 部分下)。
    • @user4844024 我刚刚从上面的示例中删除了它们,以免混淆,原因是 - 没有必要在那里使用它们,甚至可能在你的真实项目中使用它们。 MDN Getting started with CSS 有一个很棒的指南,你会从中学到很多东西。总体而言,position 不是在这种布局中使用的好选择。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-11
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    相关资源
    最近更新 更多