David
David

Reputation: 953

Indent text following a <br>

I have a web page that presents flowing text, with line breaks (br) interspersed inside span tags. I would like every span that follows a br to have an indent. Is it possible to do this with pure CSS? I would prefer to do this without manipulating the text itself. (it's possible, but messy) Note that the br tags are inside the span tags.

Here is some example code and my attempt at doing it in pure CSS.

.text + br {
  text-indent: 1.5em;
}
.text > br + .text {
  text-indent: 1.5em;
}
<span class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span>
<span class="text">Donec accumsan tortor at maximus vehicula.<br></span>
<span class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span>
<span class="text">Donec accumsan tortor at maximus vehicula.<br></span>

Update: this may be impossible to do in pure CSS. My project utilizes jQuery so a solution using jQuery is acceptable.

Update 2: text-indent in CSS is only supported for block elements. Using display: block on the span tags will make indentation work, but then the content needs to be merged between span tags to prevent any unwanted block element newlines. An alternative is to insert a number of &nbsp; instead of setting a CSS class.

Upvotes: 0

Views: 2047

Answers (2)

Mike Loffland
Mike Loffland

Reputation: 334

I don't believe there are any css selectors that will allow you to target the parent element if it contains a given child. You may be forced to use JavaScript (unless you're willing to massage the data in such a way that will allow you to use css selectors for the desired formatting).

A jQuery solution is shown below:

$( ".text:has(br)" ).next(".text").addClass( "indent" );
span {
    display:block;
}
.indent {
    text-indent: 1.5em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<span class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span>
<span class="text">Donec accumsan tortor at maximus vehicula.<br></span>
<span class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span>
<span class="text">Donec accumsan tortor at maximus vehicula. asdfasdfasdf a<br></span>

Upvotes: 3

userDEV
userDEV

Reputation: 535

since text-indent only applies to block-level elements, maybe this may work for you

$(document).ready(function(){

    $("p").css("text-indent","1.5em");
	

});
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

</head>

<body>
<p class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Donec accumsan tortor at maximus vehicula.<br/>
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Donec accumsan tortor at maximus vehicula.<br/></p>



</body>

</html>

Upvotes: -1

Related Questions