2017-07-16 225 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