css 中float後text-align無效解決辦法

來源:互聯網
上載者:User

般寫內容置中的時候都會使用text-align:center屬性,但是內元素一旦float起來的時候,text-align就會失效。
我們只能其他的方法來達到置中的目的

 代碼如下 複製代碼

<!DOCTYPE HTML>
<html lang="en-US">
<head>
 <meta charset="UTF-8">
 <title>float置中的最佳實務</title>
 <style type="text/css">
  *{margin:0; padding:0;}
  ul{list-style-type:none;}
  
  .container{width:600px; padding:5px; border:2px solid #ddd; margin:30px auto; overflow:hidden; text-align:center;}
  .container h2{font-size:14px; padding:10px 0;}
  
  .sl-float-middle{position:relative; left:50%; float:left;}
  .sl-float-middle-cell{position:relative; float:left; right:50%; height:30px; line-height:30px; margin:0 5px; border:5px solid #f2f2f2;}
  .sl-float-middle-cell img{height:30px;}
 </style>
</head>
<body>
 <div class="container">
  <h2>float置中的最佳實務</h2>
  <ul class="sl-float-middle">
   <li class="sl-float-middle-cell">寬度一</li>
   <li class="sl-float-middle-cell">寬度二二二</li>
   <li class="sl-float-middle-cell">三</li>
   <li class="sl-float-middle-cell"><img src="IMG_20111114_154154-300x225.jpg" alt="來一張圖片" /></li>
  </ul>
 </div>
</body>
</html>

本方案主要是利用父層ul的float:left+left:50%,配合子層li的float:left+right:50%(left:-50%)來達到目的的。
html代碼如下:

 代碼如下 複製代碼

<ul class="sl-float-middle">
 <li class="sl-float-middle-cell">寬度一</li>
 <li class="sl-float-middle-cell">寬度二二二</li>
 <li class="sl-float-middle-cell">三</li>
 <li class="sl-float-middle-cell"><img src="IMG_20111114_154154-300x225.jpg" alt="來一張圖片" /></li>
</ul>

css代碼如下:

 代碼如下 複製代碼

.sl-float-middle{position:relative; left:50%; float:left;}
.sl-float-middle-cell{position:relative; float:left; right:50%;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.