2012-07-25 35 views
1

例如也許我的HTML是下列之一:如何居中任意一塊HTML?

  • 文本<p>其寬度沒有整體寬度設定爲400
  • 一個形式的輸入一把設置
  • 一個<table>與沒有整體寬度爲
  • 或其他任何

換句話說 - 您居中上述任何他們自然向左前。是否有可能以HTML爲中心?

編輯:讓我澄清更多。 HTML塊可以是任何內容:內聯,塊,三個div和2個ps,5個表格和一個div,一個div內的div等等。這個html塊不知道它會被居中,它不是允許居中。我想要的東西 - 讓我們把這個塊的HTML包裝在一個父div中,然後只在父div上使用CSS。有些東西是你沒有調整HTML塊的地方。我希望它水平居中不垂直。如果它仍然在左邊,我想讓它呈現。

+0

看看我的答案。 #canvas的定位正是你所要求的。 – 2012-07-25 07:40:23

回答

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

+0

'

'正在爲我工​​作。使用它有什麼問題嗎? – Ryan 2012-07-25 07:44:06

+0

因爲這是舊技術它用於只有新聞信 – 2012-07-25 07:55:22

+0

不明白,你能說另一種方式嗎? – Ryan 2012-07-25 08:10:16

0

如果你想集中設置元素的另一個元素,分配子元素相對定位,或只是默認定位(絕對定位不會做! ),給它一個固定的寬度,將其邊距設置爲0 auto,並且它將在父元素內水平居中。當然,沒有辦法將元素垂直居中,你必須自己明確地做。

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; 
} 

希望幫助你。

+0

nope。不允許觸摸中間的任意塊。所以在你的情況下,你只能在canvas div和裏面使用CSS,可以是任何東西(這個東西不知道它是居中的,不允許居中)。 – Ryan 2012-07-25 07:43:24

+0

你錯過了這一點。無論它是如何嵌套,您都可以對任何定位元素執行此操作。以上是我爲了簡單起見而舉的例子。 – 2012-07-25 07:45:36

+0

試試看我們的Ryan,給一個容器DIV一個寬度,然後給它一個margin:0 auto。它將集中在它的父母身上。 – 2012-07-25 07:47:24