Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one draw a box around some sibling HTML elements?

Tags:

html

css

I'd like to visually highlight a set of sibling elements that share the same attribute.

#boxed_contents span[data-boxme] {
  display: inline-block;
  border: 2px solid #00F;
  border-radius: 5px;
}
<div id="boxed_contents">
    <span>hello</span><!--
 --><span>world</span><!--
 --><span data-boxme>look</span><!--
 --><span data-boxme>at</span><!--
 --><span data-boxme>me</span>
</div>

This almost works like I want it to, but I'd like to join the boxes around each of the boxme elements, leaving just one box around all three elements. I know I can wrap the adjacent boxme elements in a wrapper div, but since this is conceptually a visual (rather than a structural) choice, I'd really like to do this without modifying the HTML.

Is there a way to do this in pure CSS? Failing that, with the addition of some straightforward Javascript?

like image 463
user108471 Avatar asked Apr 26 '15 19:04

user108471


1 Answers

Actually it is not possible to wrap elements in a another one by pure CSS. But we can somehow fake the effect by adding border to each adjacent element and putting an absolutely positioned pseudo-element over the middle borders.

As an aside, note that custom attributes are not valid in HTML unless they are formatted as data-*.

#boxed_contents [data-boxme] {
  display: inline-block;
  border: 2px solid #00F;
}

#boxed_contents [data-boxme] + [data-boxme] {
  margin-left: -.25em;
  padding-left: .25em;
  position: relative;
}

#boxed_contents [data-boxme] + [data-boxme]:after {
  content: "";
  position: absolute;
  top: 0; bottom: 0; left: -4px;
  width: 4px;
  background: white;
}
<div id="boxed_contents">
  <span>hello</span>
  <span>world</span>
  <span data-boxme>look</span>
  <span data-boxme>at</span>
  <span data-boxme>me</span>
  <span>not me</span>
</div>
like image 102
Hashem Qolami Avatar answered Oct 06 '22 05:10

Hashem Qolami