来自CMS的内联CSS

时间:2014-08-22 20:35:39

标签: php html css

这个问题纯粹是出于好奇。 我非常挑剔我的代码的整洁,我讨厌使用内联样式,但是我找到了一个用例,我没有看到任何方法不实现它们。

我正在CMS中构建一个部分,允许用户创建多个页面部分,并进行大量自定义,页面可能看起来像

[    section A    ]    <--- Has an image, custom margins and padding set for content
[    section B    ]  
[    section C    ]    <--- custom margins and paddings set on this section

目前我有3个数据库表,一个支持该部分的基本信息,如媒体链接,标题,副标题等。另一个支持切换选项,例如排除容器溢出,水平/垂直对齐文本然后是第三个表,它存储有关该表的特定值的信息,即文本上设置的填充或自定义边距,或图像的缩放%年龄。

现在,当我的页面加载时,我会为每个部分提取所有数据,并遍历一个数组,使用PHP为我的元素内联指定样式:

function build_left_section($section) {
// Echo the standard section piece
echo '<section class="section_wrapper section_overflow" style="background:'.$section['section_color'].'; height:'.$section['height'].'px">';
echo '<div class="content row">';
      $this->get_borders($section);
echo '
     <div id="left_col" class="image_column grid_6 ' . $this->get_width($section, 'left') . '">
        <img id="image" src="'. $section['media_link'] .'" alt="'. $section['tags'] .'" style="margin-left:'. $section['image_x'] .'%; margin-top:'. $section['image_y'] .'%; width:'. $section['image_zoom'] .'%;">
     </div>

     <div id="right_col" class="text_column grid_6 ' . $this->get_width($section, 'right') . '">
        <div class="text_move" style="margin-left:'.$section['text_x'].'%; margin-top:'.$section['text_y'].'%">
            <div class="text_wrap '.$this->get_text_alignment($section).'" style="padding-left:'.$section['text_padding'].'px; padding-right:'.$section['text_padding'].'px;">
                '.$this->get_text($section).'
            </div>
        </div>
     </div>
     ';
}

我讨厌这段代码看起来多么混乱,而且我确信由于它填充了我的HTML文档的大小,有一些相当大的性能缺点,我还读到了可能会导致缓存问题的地方。

有没有人对如何更有效地达到相同结果有任何建议?

提前致谢。

1 个答案:

答案 0 :(得分:2)

这是自定义CMS中非常常见的情况,您可以这样做:

将内联样式移动到内部工作表。例如,这部分:

<div id="left_col" class="image_column grid_6 ' . $this->get_width($section, 'left') . '">
        <img id="image" src="'. $section['media_link'] .'" alt="'. $section['tags'] .'" style="margin-left:'. $section['image_x'] .'%; margin-top:'. $section['image_y'] .'%; width:'. $section['image_zoom'] .'%;">
     </div>

变为:

<div id="left_col" class="image_column grid_6 ' . $this->get_width($section, 'left') . '">
        <img class="my_image" src="'. $section['media_link'] .'" alt="'. $section['tags'] .'" />
     </div>

现在,您可以在页面中调用内部CSS:

margin-left:'. $section['image_x'] .'%; 
margin-top:'. $section['image_y'] .'%; 
width:'. $section['image_zoom'] .'%;"

这就是更清洁,可重复使用的代码。

另外,我注意到你正在滥用div ID。尝试使用类并确保正确关闭标记(在此示例中,我关闭了图像标记)