2017-07-16 131 views
0

設計標題。這是應該喜歡什麼減少css中的重複代碼

enter image description here

HTML

<header> 
    <div id="primary-header"> 
     <div id="logo">logo</div> 
     <div id="social-media">social media</div> 
     <div id="search">You search here</div> 
     <div id="login">Login</div> 
    </div> 
    <div id="secondary-header"> 
     <div id="category">for category</div> 
     <div id="menu">If you have menu</div> 
     <div id="cart">well another column, add a cart</div> 
    </div> 
</header> 

CSS

#primary-header, #secondary-header {clear: both; margin: 0; padding: 0;} 
#primary-header::before, #secondary-header::before, 
#primary-header::after, #secondary-header::after { content: ""; display: table; } 
#primary-header::after, #secondary-header::after { clear: both; } 

#logo { display: block; float: left; margin: 1% 0 1% 1.6%; margin-left:0; width: 15.33%;} 
#social-media { display: block; float: left; margin: 1% 0 1% 1.6%; width: 6.86%; } 
#search {display: block; float: left; margin: 1% 0 1% 1.6%; width: 49.2%;} 
#login {display: block; float: left; margin: 1% 0 1% 1.6%; width: 23.8%;} 
#category {display: block; float: left; margin: 1% 0 1% 1.6%; margin-left:0; width:15.33%} 
#menu{display: block; float: left; margin: 1% 0 1% 1.6%; width:57.66%} 
#cart {display: block; float: left; margin: 1% 0 1% 1.6%; width:23.8%} 

JSFiddle

css必須在此處重複許多屬性。如果您看到display: block; float: left; margin: 1% 0 1% 1.6%;正在重複6-7次。有沒有辦法有效地寫出減少重複量的CSS?

回答

1

化妝使用的一類,可以減少你的代碼

.item { display: block; float: left; margin: 1% 0 1% 1.6%; } 

#logo {margin-left:0; width: 15.33%;} 
#social-media { width: 6.86%; } 
#search { width: 49.2%;} 
#login { width: 23.8%;} 
#category { margin-left:0; width:15.33%} 
#menu{ width:57.66%} 
#cart {width:23.8%} 



<header> 
    <div id="primary-header"> 
     <div class="item" id="logo">logo</div> 
     <div class="item" id="social-media">social media</div> 
     <div class="item" id="search">You search here</div> 
     <div class="item" id="login">Login</div> 
    </div> 
    <div id="secondary-header"> 
     <div class="item" id="category">for category</div> 
     <div class="item" id="menu">If you have menu</div> 
     <div class="item" id="cart">well another column, add a cart</div> 
    </div> 
</header> 
+0

謝謝約翰。 – Mecom

0

你只需要幾個CSS規則來實現該標記,如下面,採用相同的規則與逗號分隔不同的元素才能真正減少代碼

div#primary-header div, div#secondary-header div { 
    display: inline-block; 
    text-align:center; 
} 
#logo, #category{ width: 15%; } 
#social-media{ width:10%; } 
#search{ width:40%; } 
#login{ width:20%; } 

這裏是一個fiddle

0

使用SASSLESS。使用這些框架之一編寫CSS可以顯着減少您必須手動編寫的代碼量。

0

您正在使用'div',因此'display:block'超出。此外,'float:left/right'默認添加'display:block'。 Look here