1

例如,也许我的 HTML 是以下之一:

  • <p>宽度设置为 400 的文本
  • 具有少量输入且未设置整体宽度的表单
  • a<table>没有设置整体宽度
  • 或其他任何东西

换句话说 - 在您将上述任何内容居中之前,它们自然会位于左侧。是否可以将 HTML 居中?

编辑:让我澄清更多。HTML 块可以是任何东西:内联、块、三个 div 和 2 个 ps、5 个表和一个 div、一个 div 内的 div 等等。html 块不知道它会被居中,它不是允许居中。我想要一些类似的东西 - 让我们将这段 HTML 包装在父 div 中,然后仅在父 div 上使用 CSS。类似于您没有调整 HTML 块的内容。我希望它水平居中而不是垂直居中。我希望它像它仍然在左侧一样渲染。

4

3 回答 3

1

嘿有两个选项第一个是非常旧的选项

<center>
//your html any element 
</center>

但这是非常古老的方法

新选项是

你可以像这样习惯

css

.ok{
border:solid 1px red;
  width:400px;
  text-align:center;
}
table{
margin:0 auto;
}

HTML

<div class="ok">

<p>
Hello
</p>

<a href="#">a</a>
<form>
<input type="text">
</form>

  <table border="1">
    <tr><td>hi</td></tr>
  </table>

  </div>

现场演示http://tinkerbin.com/j1A3HIK9

于 2012-07-25T07:10:06.637 回答
0

如果你想将一个元素设置在另一个元素的中心,给子元素分配相对定位或者只是默认定位(绝对定位不行!),给它一个固定的宽度,将它的边距设置为0 auto,它会水平居中在父元素。当然,没有办法让元素垂直居中,你必须自己明确地做到这一点。

于 2012-07-25T07:17:19.277 回答
0

是的,您提到的所有元素都是可能的。

拿这个 HTML:

<body>

<div class="canvas">

    <p>This is a really lovely but meaningless piece of text</p>

    <div class="form-container">

        <form>

            <input type="text" name="example" placeholder="Enter some example text" />

        </form>

    </div>

</div>

</body>

所以我们想要将一些元素居中。让我们从包含 DIV #canvas 开始,然后从那里开始。

/* First a very crude reset on <body> and declare it's dimensions */

body {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
}

/* Next we must declare a definitive width of our #canvas to allow
   us to centre itself and elements within it. */

#canvas {
    width:960px;
    position:relative;
    margin: 0 auto; /* This 'auto' on left / right margin centers it
}

/* Note that <p> tags are auto 100% width so centering them is not
   going to do anything with the above technique. Instead: */

#canvas p {
    text-align: center;
}

/* Now form elements, no need to style <form> it is a meta container
   and really shouldn't be used for anything other than that, lets
   style the actual input elements instead */

#canvas form input {
    width: 30%; /* Lets define a width so that we can center it in */
    margin: 0 auto;
}

希望对您有所帮助。

于 2012-07-25T07:28:39.013 回答