首页 > 解决方案 > 如何在标题和段落下创建具有不同颜色的图块?

问题描述

我是 CSS 新手,并尝试对其进行一些试验,这样我就可以开始制作页面,而不会因缺乏经验而积累错误代码。

在下面的代码片段中,我编写了一个带有黑色边框和顶部浅灰色背景的面板/图块。整个.tile班级都有一些填充(1em),这很好。

h2但是假设我想通过在下面和h5 整个瓷砖长度上使用更深的灰色来提供更多“颜色” ,就像这样 在此处输入图像描述

我应该怎么做?

如果可能的话,我会避免负边距/填充或其他类似技巧的东西来完成任务。

/* stuff I always put */
:root {
  box-sizing: border-box;
  margin: 1em;
}
*,
::after,
::before {
  box-sizing: inherit;
  margin: 0;
}
body * + * {
  margin-top: 1.5em;
}

/* for demo only */
:root {
  box-sizing: border-box;
  margin: 1em;
}

/* stuff for the question */
.tile {
  border-style: solid;
  border-color: black;
  border-width: .5em 0 0 0;
  background-color: hsl(0,0%,90%);
  padding: 1em;
}
<div class="tile">
  <h2>Title</h2>
  <h5>Long subtitle here</h5>
  <p>Sunt in culpa qui officia deserunt mollit anim id est laborum
  consectetur adipiscing elit, sed do eiusmod tempor incididunt ut
  labore et dolore magna aliqua. Ut enim ad minim veniam, quis
  nostrud exercitation ullamco.</p>
</div>

标签: htmlcss

解决方案


我认为这将是一种更简单/更清洁的方式来逐块管理它。

您应该使用rem而不是em指定块的位置。实际上,虽然rem大小基于html大小,但em基于父大小。

例子:

html, body{
  font-size: 16px ;
}

#parent-1, #parent-2{
  background:red;
}
#parent-1 h1, #parent-2 h1{
  background: grey;
}

#parent-1{
  font-size:60px;
}
#parent-1 h1{
  font-size:0.5em; /* So equal to 30px */
  padding: 1em 2em;
  margin: 1em;
}

#parent-2{
  font-size:60px;
}
#parent-2 h1{
  font-size:.5rem;  /* So equal to 8px */
  padding: 1rem 2rem;
  margin: 1rem;
}
<div id="parent-1">
  <h1>I am with EM</h1>
</div>

<div id="parent-2">
  <h1>I am with REM</h1>
</div>

演示

/* stuff I always put */
:root {
  box-sizing: border-box;
  margin: 1em;
}
*,
::after,
::before {
  box-sizing: inherit;
  margin: 0;
}
body * + * {
  margin-top: 1.5em;
}

/* for demo only */
:root {
  box-sizing: border-box;
  margin: 1em;
}

/* stuff for the question */
.tile {
  border-style: solid;
  border-color: black;
  border-width: .5em 0 0 0;
  background-color: hsl(0,0%,90%);
  /*padding: 1em;*/
}
h2, h5{
  background-color: grey;
  margin:0;
}
h2, h5, p{
  padding:1rem;
}
<div class="tile">
  <h2>Title</h2>
  <h5>Long subtitle here</h5>
  <p>Sunt in culpa qui officia deserunt mollit anim id est laborum
  consectetur adipiscing elit, sed do eiusmod tempor incididunt ut
  labore et dolore magna aliqua. Ut enim ad minim veniam, quis
  nostrud exercitation ullamco.</p>
</div>


推荐阅读