CSS place elemtent at position of another (NOT parent) - html

I have an XML file which consists mostly of text. However, there are some element in there containing additional information. Let's call these additional information bits "element". In some paragraphs there is none of these, in some paragraph several. Sometimes there are even right after each other. However, in different paragraphs they are always at different positions.
Here's mock up:
<paragraph>
Qui <element>20</element> corti. num sit <element>10</element><element>5</element> igitu pugis quium. quem er Epiendis nessictilluptiudicaribus? qui ipsarent scit verspitomnesse con eiudicitinec tam ret pari Graeperi diurum eo <element>50</element> nebituratam num aerminxeato nilibus. nostereffer est modulceribus, ficantendus anonea Chraectatur, quemodumquae ut pet sum re vivatotertentu vitra cortem nonemod hunturunclia dolum poraectiatiamas rein eximplatorefut egra vartere
</paragraph>
Now I want to transform this XML file into HTML with XSLT. The problem is: The "additonal elements" should appear nowhere in the text, but at a separate column. Like this:
As you can see, the numbers (bearing my "additional information") appear right at the level where they are in the text: "20", "10" and "5" are at the first line, because in the XML source data they are are referenced after the words "Qui" and "sit", which are in the output both at the first line in the text. "50" is right at the level of "eo" nebituram".
How can I achieve this behaviour with CSS?
It is rather easy to put an anchor element in the HTML at this very same position:
eo <a id="some_id"/> nebituratam
Let's say that the "50" is in a span-element
<span stlye="...">50</span>
However, what do I put in the CSS here? Is there a way to state in CSS to place this span right at the level of the anchor with the id "some_id"?
Of course, the anchor can in no way be the parent of the span element.
Honestly, I'm quite sure that my problem is unsolvable without JavaScript or something, but I'd like to avoid skripts wherever I could.

Try This
p{
padding-left:50px;
position:relative;
}
p span{
position:absolute;
left:10px;
top:45%;
font-size:16px;
font-weight:bold;
}
<p>Qui corti. num sit igitu pugis quium. quem er Epiendis nessictilluptiudicaribus? qui ipsarent scit verspitomnesse
con eiudicitinec tam ret pari Graeperi diurum eo <span>50</span> nebituratam num aerminxeato nilibus. nostereffer est modulceribus,
ficantendus anonea Chraectatur, quemodumquae ut pet sum re vivatotertentu vitra cortem nonemod hunturunclia dolum
poraectiatiamas rein eximplatorefut egra vartere</p>

Related

Change style inside HTML to all class elements

I was wondering couple days ago if its possible to do the following.
Lets say we have a basic HTML code with the following in it:
<p class="someinfo"> basic text </p>
<p class="someinfo"> some other information </p>
And we also have some CSS files that are included in the header of the HTML with basic styling like:
.someinfo{
font-size:32px;
color:red;
}
So here comes my question.
If I edit the HTML and put inside the first Paragraph (style="color:black") like down below it will change the color only for that div element.
By changing the style like this is it somehow possible to make the changes appear to all elements with that class name?
<p style="color:black" class="someinfo"> basic div </p>
<p class="someinfo"> some other information </p>
I hope you understand what I'm asking and apologise if it's a stupid question.
P.S. I am asking this because I have the following situation. There is a website that i don't have the access to any of the files on the server, cannot upload any new files. All i can do is create new pages from a text editor which doesn't recognise < style > and < script > tags. All I want to do is change some css on the navigation and on some other items that are part of every page in the website.
This is what CSS is for :) If you want all elements of a given class name to change to black you could change the CSS style to:
.someinfo{
font-size:32px;
color:black;
}
Doing it inline manually wont work.
If you really want to do it inline you could do so programatically with js:
var someInfoElements = document.getQuerySelectorAll(".someinfo");
for(i = 0; i < someInfoElements.length; i++) {
someInfoElements[i].style.color = "black";
}
Option 1
You could define the first element with a style attribute and use JS to make the rest for you, as long as all elements have the same selector.
const someInfo = document.querySelectorAll('.someinfo');
const style = someInfo[0].getAttribute("style");
someInfo.forEach((s) => s.style = style);
<p style="color:red; font-size:32px" class="someinfo"> basic text </p>
<p class="someinfo"> some other information </p>
Option 2
You could add style attributes to each element.
Here is an example:
const someInfo = document.querySelectorAll('.someinfo');
let style = '';
someInfo.forEach((s) => {
if (typeof s.getAttribute("style") === 'string') {
style += s.getAttribute("style");
if (style.slice(-1) !== ';') {
style += ';';
}
}
});
someInfo.forEach((s) => s.style = style);
<p style="color:red;" class="someinfo"> basic text </p>
<p style="font-size:32px" class="someinfo"> some other information </p>
<p style="color:blue" class="someinfo"> and more information </p>
<p class="someinfo"> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Numquam, soluta animi, optio repellat eius consectetur! Iure repudiandae, architecto doloremque, dolorum totam consequatur minima placeat recusandae nisi earum dignissimos, illum culpa. </p>
As you see I am using color:red and color:blue. Just like in CSS the last attribute wins. In this case the color of your element with the class someinfo is blue and all other CSS attributes and values will be added.
yes you can, if you want to change all paragraph in the div just put "p" in your css code like this: your both elements will change
p {font-size:32px;color:red;}
instead of
.someinfo{font-size:32px;color:red;}
your code will be like this
<style> p { font-size:32px;color:red;} </style>

Delete an HTML element containing a pattern

How can I delete elements (from <span> to </span>) whose text contain PATTERN in it? The contents of the element should be deleted along with the element.
For example, I want to delete the first <span>...</span> element in the following:
<span><SPAN>some text with
with </SPAN> a PATTERNin it etc</span><span><SPAN>some text
without </SPAN> a thingIn it etc</span>
to produce, using SED only :
<span><SPAN>some text
without </SPAN> a thingIn it etc</span>
PS: No help with end of lines or solo words, it must just detect any <span>...</span> and PATTERN.
Production server only allow basic commands such as SED.
I'm currently using the following but it's ugly and doesn't seem to work.
sed '/<span.*\n.*PATTERN.*<\/span>/d'
If HTML:
perl -MXML::LibXML -e'
my $parser = XML::LibXML->new();
my $doc = $parser->parse_html_file($ARGV[0]);
$_->unbindNode()
for $doc->findnodes(q{//span[contains(text(), "PATTERN")]});
binmode(STDOUT);
print($doc->toString());
' in.html >out.html
If XHTML:
perl -MXML::LibXML -e'
my $parser = XML::LibXML->new();
my $doc = $parser->parse_file($ARGV[0]);
my $xpc = XML::LibXML::XPathContext->new();
$xpc->registerNs( h => "http://www.w3.org/1999/xhtml" );
$_->unbindNode()
for $xpc->findnodes(q{//h:span[contains(text(), "PATTERN")]}, $doc);
binmode(STDOUT);
print($doc->toString());
' in.xhtml >out.xhtml
The above both produce the following (with some implied elements vivified):
<span><SPAN>some text
without </SPAN> a thingIn it etc</span>

Insert a logo in upper right corner of R markdown html document

I'm trying to put my company logo on the right corner of my html document
Here my code:
<script>
$(document).ready(function() {
$head = $('#header');
$head.prepend('<div class="knitr source"><img src="logo.png" width="220px" align="right" ></div>')
});
</script>
---
title: "Title"
author: "Author"
date: "Date"
theme: bootstrap
output: html_document
keep_md: true
---
```{r echo=FALSE, include=FALSE}
knitr::include_graphics('./logo.png')
```
<br>
## 1) Header
<br>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo.
However, because the logo.png is a local file when sharing the html document people are not able to see it.
Additionally, I tried the following approach
---
title: "Title"
author: "Author"
date: "Date"
output:
html_document:
css: markdown.css
includes:
in_header: extLogo.html
---
where extLogo.html
<div class="logos"><img src="logo.png" width="220px" align="right"></div>
But it creates a div outside the div where the Title is (<div class="container-fluid main-container">). Can anyone help on this?
You can use htmltools::img with a little inline CSS for positioning. src can take a path directly, but when images aren't just handled like plots, sometimes knitting fails to convert images to a URI properly, which in turn causes them to fail to render. Using self_contained: false in the YAML is a quick solution, but it's not much harder to use knitr::image_uri to manually convert the image:
---
title: "Title"
author: "Author"
output: html_document
---
```{r, echo=FALSE}
htmltools::img(src = knitr::image_uri(file.path(R.home("doc"), "html", "logo.jpg")),
alt = 'logo',
style = 'position:absolute; top:0; right:0; padding:10px;')
```
---
# 1. Header
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor.
The accepted answer works if you are using classical html output. If like me, you also work with bookdown, the logo need to appear on every pages. So, in case somebody find this answer but want to add a logo with bookdown, I give my proposition:
We need to create an external file with a script to be called in header, thankfully we can create it directly in the rmarkdown script.
We also use htmltools::img to allow including the image without external image file.
Here is my rmarkdown script to be used as an example:
---
title: "Logo with Bookdown"
author: "Author"
date: '`r format(Sys.time(), "%d %B, %Y")`'
output:
bookdown::gitbook:
includes:
in_header: header.html
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r htmlTemplate, echo=FALSE}
# Create the external file
img <- htmltools::img(src = knitr::image_uri(file.path(R.home("doc"), "html", "logo.jpg")),
alt = 'logo',
style = 'position:absolute; top:50px; right:1%; padding:10px;z-index:200;')
htmlhead <- paste0('
<script>
document.write(\'<div class="logos">',img,'</div>\')
</script>
')
readr::write_lines(htmlhead, path = "header.html")
```
# Page 1
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r cars}
summary(cars)
```
# Page 2
You can also embed plots, for example:
```{r pressure, echo=FALSE}
plot(pressure)
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
I took a quite different approach to the answers above, using only CSS and without absolute positioning. I added the following CSS code chunk to my document, but you can also create a standalone CSS file and include that in the Rmd YAML header.
```{css, echo=FALSE}
#header {
background-image: url("data: BASE64 encoded string for image");
background-repeat: no-repeat;
background-position: 95%;
padding: 5px;
}
#header > * {
max-width: calc(100% - 225px);
}
#media only screen and (max-width:600px){
#header > .title {
margin-top: 105px;
}
#header > *
max-width: 100%;
}
#header {
background-position: 10px 10px;
}
}
```
There's a few things going on here. To address the original question about the image, you need to base64 encode the image yourself and put the string into the background-image URL.
It also handles the issue of overlap of logo and header content in a reactive way, setting max-width on all header elements, and placing the logo above the title on narrow windows (less than 600px).
If you don't care about overlap at all, then you only really need the first #header selector code. If you don't care about the narrow device reactive layout then you can keep the first two selectors and drop the #media block.
The two pixel values 225px and 105px are based on my logo, and will need to be changed to fit your image plus some padding.
#alistaire's accepted answer was really useful. However in my case the title and the logo were overlapping, since the title in my markdown is really long.
Looking around I came up with the following solution, and I post it in case is useful for anybody.
```{js logo-js, echo=FALSE}
$(document).ready(function() {
$('#header').parent().prepend('<div id=\"logo\"><img src=\"www/xxxxx.png\" style=\"position:absolute; top:0; right:0; padding:20px; height:120px\"></div>');
$('#header').css('margin-right', '120px')
});
```
This should be added anywhere in the markdown, and of course it only works for HTML output. The idea is to add a new div for the logo, and then add a margin-right to the title so that it does not overlap.
Note that I don't think this is really optimal; my use of css is clumsy and if somebody figures out a better way I'm glad to hear. Anyhow it seems works ok.
As a complement to alistaire answer, and answering the question from Marco. One can use width, and height to select the size of the figure. For example,
---
title: "Title"
author: "Author"
output: html_document
---
```{r, echo=FALSE}
htmltools::img(src = knitr::image_uri(file.path(R.home("doc"), "html", "logo.jpg")),
alt = 'logo',
style = 'position:absolute; top:0; right:0; padding:10px;',
width = "300px",
heigth = "300px")
```
---
# 1. Header
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor
In case you make a rmarkdown website and you would like to add a logo to the right in the navbar:
In the _site.yml include a before_body:
include:
before_body: logo.html
In the html template:
<script type="text/javascript">
$(function() {
$('.navbar-right').before($('.logo'));
})
</script>
<div class="logo pull-right">
<img src="logo.png" alt="logo" width="150" style="margin-top: 15px;">
</div>
Key is to include the pull-right class in the div you insert.
To get the logo top right aligned inside the header div, do this:
Make file called header-logo.html containing:
<script>
$(document).ready(function() {
$('#header').prepend('<img src="https://via.placeholder.com/350x350" style="float:right" width="30%"/>');
});
</script>
Update your .Rmd with:
output:
html_document:
includes:
in_header: header-logo.html
base64 encode the logo manually and replace the url in src if you want the .HTML be self contained.

Unwanted breakline behavior - general explanation

I have experienced cross-browser problem that a line on a page in a narrow column is breaked too early despite the space left where the last word could easily fit.
Firstly I thought there is something wrong with my stylesheet but it looks the same in a simple fiddle which I created (no php tags, no line-breakers, etc.):
I am sorry as it's in Czech Language but for demo purpose I hope it's ok.
It shows the same bug in FF,IE and Chrome on Win7 and Win8, even on iPad.
Link to fiddle: http://jsfiddle.net/Grows/q9wqeu14/1/
Demo:
HTML:
<div class="column">
<p>Jsme tým zkušených profesionálů, který Vám pomůže s kompletním IT řešením. Spravujeme IT techniku jak menším firmám do deseti uživatelů, tak i velkým společnostem se stovkami stanic a desítkami serveů. Náklady na externí správu sítě jsou zcela individuální a závisí na rozsahu sítě (počet serverů, stanic, aktivních prvků apod.), dohodnuté frekvenci návštěv a garantované době servisních zásahů. U menších firem se tato částka obvykle pohybuje v jednotkách tisíců korun měsíčně, takže se určitě vyplatí více, než zaměstnávat vlastního správce sítě.</p>
</div>
<div class="column">
<ul>
<li>Individuální přístup a vstřícnou péči o uživatele výpočetní techniky</li>
<li>Pravidelnou údržbu výpočetní techniky - minimalizují se její výpadky</li>
<li>Garanci servisního zásahu - minimalizuje ztráty způsobené výpadkem</li>
<li>Řízení IT procesů - provozujeme systém HELPDESK pro hlášení servisních požadavků, telefonickou linku HOT-LINE a automatický monitorovací systém NAGIOS, který nepřetržitě monitoruje chod Vašich klíčových zařízení</li>
<li>Poradenství a konzultační služby</li>
</ul>
</div>
<div class="column">
<ul>
<li>Finanční úspora - IT specialistu využíváte jen tehdy, je-li to potřeba. Ušetříte na mzdových nákladech, odborných školeních apod.</li>
<li>Flexibilita - služba je smluvně garantovaná, nemusíte řešit nemoci, dovolené, zástupy apod.</li>
<li>Profesionalita - pracujeme v týmu, máme zkušenosti, kvalitní technické zázemí a podporu našich dodavatelů. Jsme schopni minimalizovat rizika výpadku sítě či je zkrátit na minimum.</li>
<li>Přenesení zodpovědnosti za bezproblémový chod Vaší sítě na dodavatele</li>
</ul>
</div>
CSS:
body {
font-size: 14px; font-family: 'Arial'; text-align: left;
}
.column {
width: 214px; border: 1px black solid;
}
li {
list-style-type: disc; list-style-position: outside;
}
What me and both my client see is the weird break between 3rd and 4th row but also in more text.
I tried to search similar questions here and Google it but no success.
Is this a standard browser behavior or there is something wrong?
I really don't want to use manual line-breakers like br, wbr, nbsp, etc.
Thanks a lot!
Cheers, Martin
---- UPDATED ----
Thanks for the given solutions guys so far.
There are no white-spaces of any kind it's just pure text, so I can't remove any.
Also it must stay in three divs.
I guess it's some weird behavior of czech language in browser but I didn't see something like this before.
Maybe I can't do anything with it and this could be an answer too :)
---- SOLVED ---
Emmanuel was right.
There was something weird with some space characters. When I deleted them and typed space again, it dissapeared. Thank you so much! If someone explain this to me I would be very happy because in the source-code there weren't any visible "white-space" like tags...
See Remove non breaking space from <h4>. In your editor, search for non-breaking spaces if you know how to do that, turn on a mode which displays them, or do a search-and-replace of non-breaking spaces with regular old sp0aces.
Remove second and third div like this:
<div class="column">
<p>Jsme tým zkušených profesionálů, který Vám pomůže s kompletním IT řešením. Spravujeme IT techniku jak menším firmám do deseti uživatelů, tak i velkým společnostem se stovkami stanic a desítkami serveů. Náklady na externí správu sítě jsou zcela individuální a závisí na rozsahu sítě (počet serverů, stanic, aktivních prvků apod.), dohodnuté frekvenci návštěv a garantované době servisních zásahů. U menších firem se tato částka obvykle pohybuje v jednotkách tisíců korun měsíčně, takže se určitě vyplatí více, než zaměstnávat vlastního správce sítě.</p>
<ul>
<li>Individuální přístup a vstřícnou péči o uživatele výpočetní techniky</li>
<li>Pravidelnou údržbu výpočetní techniky - minimalizují se její výpadky</li>
<li>Garanci servisního zásahu - minimalizuje ztráty způsobené výpadkem</li>
<li>Řízení IT procesů - provozujeme systém HELPDESK pro hlášení servisních požadavků, telefonickou linku HOT-LINE a automatický monitorovací systém NAGIOS, který nepřetržitě monitoruje chod Vašich klíčových zařízení</li>
<li>Poradenství a konzultační služby</li>
</ul>
<ul>
<li>Finanční úspora - IT specialistu využíváte jen tehdy, je-li to potřeba. Ušetříte na mzdových nákladech, odborných školeních apod.</li>
<li>Flexibilita - služba je smluvně garantovaná, nemusíte řešit nemoci, dovolené, zástupy apod.</li>
<li>Profesionalita - pracujeme v týmu, máme zkušenosti, kvalitní technické zázemí a podporu našich dodavatelů. Jsme schopni minimalizovat rizika výpadku sítě či je zkrátit na minimum.</li>
<li>Přenesení zodpovědnosti za bezproblémový chod Vaší sítě na dodavatele</li>
</ul>
</div>
You just need word-break: break-all; style to column. WORKING CODE
If you look specifically at:
řešením. Spravujeme
in a HEX editor, the "space" between the '.' and 'S' is actually 2 bytes:
C2 A0
C2A0 is a non-breaking space in UTF-8 HEX and a "normal" breaking space is HEX 20.
Since this is a non-breaking space, the browser doesn't consider it a valid point to break the word to line-wrap.

Selenium IDE Xpath vs Webdriver Xpath

I'm newbie with Test Automation. When I locating element through Firepath with target:
xpath=(//td[contains(#id, 'catProdTd_4723290')]/div/div[2]/h2)
Firefox founds that element and verify text.
But, when I trying to locate this element with Visual Studio 2012 and Selenium Web driver, I constantly have error: "Unable to locate element: {"method":"xpath","selector":"//td[contains(#id, 'catProdTd_4723290')]/div/div[2]/h2"}" .
I tried escaping:
//td[#id=\"catProdTd_4723290\"]/div/div[2]/h2
but nothing. When I use isElementPresent method, it founds elements.
Is there some special method or rule that should be use when writing Xpath for WebDriver ?
I defined ISelenium variable, WebDriver... Clicks works, WaitForPageToLoad works, but this can not locate element.
IWebElement we= driver.FindElement(By.XPath("//td[contains(#id, 'catProdTd_4723290')]/div/div[2]/h2"));
HTML from page:
<td class="productItem" id="catProdTd_4723290"><div class="product-details">
<div class="product-aside"> <img border="0" alt="Fork and Spoon Set" src="/_photos/store/glass-large.jpg" id="catlproduct_4723290">
</div>
<div class="product-main">
<h2 class="product-name">Fork and Spoon Set</h2>
<div class="price"><strong>$17.99</strong></div>
<hr>
<div class="attributes"></div>
<hr>
<div class="product-col-1">
<div class="qty"> Quantity: <strong><input type="text" value="1" name="AddToCart_Amount" class="productTextInput" id="Units_4723290"></strong></div>
<div class="stock">(N/A in-stock)</div>
</div>
<div class="product-col-2">
<input type="submit" onclick="AddToCart(192951,4723290,'',4,'','',true);return false;" value="Buy Now" name="AddToCart_Submit" class="productSubmitInput">
<div class="wish">Add to Wishlist</div>
</div>
<div class="product-description">
<h4>Product Information:</h4>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean
commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus
</div>
</div>
<!-- End Main -->
</div>
<!-- End Product Details -->
</td>
I must add that I try to wait during debug and with
Manage().Timeouts().ImplicitlyWait
but nothing. This happens on other places also. I using Firefox for tests
You are running into dynamic attributes.
My first recommendation to you. Switch to CSS.
My second recommendation, instead of boiling down into an entire parent-child hierarchy, why don't you just KISS!
So, lets look at your issue. You are trying to fetch the product name. Easy.. we can use classes here.
css=td.productItem h2.product-name
voila, it was that easy to fetch.. instead of having this huge ugly xpath selector, we've simplified it to a css selector.
So onto the next problem, if we have multiple of td.productItem's on the page, we can use a couple things.
Try,
css=td.productItem:nth-child(1) h2.productName
That will select the first td with class, productItem.
note: you may need to specify the td's parent.. e.g. css=div#container td.productItem:nth-child(1)
More specifics...
The reason your xpath is failing, is because of that catProdTd_4723290 id assigned to the <td> element being generated automatically, rendering that element unselectable. You can work around that, by doing starts with. for example, with css -
css=td[id^='catProdTd']
will select that <td> take note though, that there might be more than 1 element selected.
I suggest using such a method for waiting:
public bool boolWaitForElementIsDisplayed(By locator, int secondsToWait)
{
WebDriverWait Wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(secondsToWait));
try
{
var FoundElement = Wait.Until<Boolean>(d =>
{
try
{
return (d.FindElement(locator).Displayed && d.FindElement(locator).Enabled);
}
catch
{
return false;
}
});
}
catch (WebDriverTimeoutException)
{
return false;
}
return true;
}
and then check as follows:
IWebElement h2Element = null;
string xpath = "//td[contains(#class,'productItem')]/div/div[contains(#class,'product-main')]/h2";
if (boolWaitForElementIsDisplayed(By.XPath(xpath), 30))
h2Element = Driver.FindElement(xpath);
So, the problem was that page isn't loaded. Why? Because WebElement.Click() not works. Why Click not working?! I don't know.
I resolved problem with clicks using JavascriptExecutor:
IJavaScriptExecutor executor = (IJavaScriptExecutor)chauffeur;
IWebElement webel1 = chauffeur.FindElement(By.CssSelector("#nav ul:nth-child(1) li:nth-child(2) a[href='/products']"));
Instead of using
webel1.Click();
which not works, I used:
executor.ExecuteScript("arguments[0].click();", webel1);