I'm writing a document in sphinx with three main types of elements in it: headings, images and plain text. Occasionally, some elements need to be centered:
Heading
=======
.. rst-class:: center
A centered paragraph, followed by non-centered image.
.. image:: /_static/exhibit_a.png
A non-centered paragraph, followed by centered image.
.. image:: /_static/exhibit_b.png
:class: center
The regular text and image get centered just fine because I register a CSS file that looks like this:
.center { text-align: center; }
img.center {
display: block;
margin: auto;
}
However, the following does not work as intended:
.. rst-class: center
===================
A Heading 1 Element
===================
Some generic text
The reST class
(sphinx rst-class
) directive is only supposed to apply to the element that immediately follows it, but in this case, the whole section becomes center aligned, with everything in it. In this example, Some generic text
comes out centered, but should be left-aligned. In fact, centering the first heading in the document like this pretty much centers the entire document.
How do I center align a heading in a way that makes it apply only to the <h1>
tag and not the whole section?
I am using the Read the Docs theme on sphinx 1.8.0, in case that matters.
Additional Thoughts
In my case, I need to modify all <h1>
and <h2>
instances and no other headings. I know that this is trivial to do in CSS with just
h1 h2 { text-align: center; }
However, this particular document is part of a much larger project, in which I want to keep all the original styles intact. The only way to do this would be to include my CSS customization only for this one document. Is this a possible alternative?
Some More Thoughts
The error is happening because the center
class is being attached to the <div>
surrounding the whole section, not the<h1>
tag. However, I'd like to be able to allow some divs (like extended lines) to be allowed to have the center
class. Just not divs with a section
class.
The idea is to unselect the <div>
element containing the sections I want and to select the headings immediately beneath it in the CSS:
.center:not(.section), .center>h1, .center>h2 {
text-align: center;
}
This unselects the outer-level div with a section
class, but centers the headings underneath it. :not
appears to be a CSS3 feature not supported on IE8, but that doesn't bother me at all: https://stackoverflow.com/a/2482475/2988730
Using .center>h1
instead of .center h1
ensures that I only get the exact headings I label, instead of all the nested ones as well. While the latter is temptingly convenient, I will run into problems if I use it, guaranteed.